Search code examples
javascripthoisting

global variable gets hoisted when passing an array


I am sorry if there is a similar answer out their somewhere. All of the hoisting answers didn't seem to quite answer my question. I have a global variable that only seems to get "hoisted" (which I don't fully understand) when I pass an array into the function. I don't see why this changes anything.

var i = 0 //counter for show pattern


//this first function works fine. the console.log shows i = 0
 function myLoop () {           
    console.log("My loop:" + i);
    setTimeout(function () {    
       alert('hello');          
       i++;                     
       if (i < 3) {            
          myLoop();             
       }                        
    }, 3000)
 }

//this second function shows i as undefined. If I remove list, then the console logs i as 0 which is correct

function showPattern(list){
    console.log(list[0] + i);
    setTimeout(function(){      
        console.log("IT works!");
        //for each square on the screen
        $(".square").each(function(j,obj){
            console.log($(obj).attr("id") + "/" + list[i]);
            //if the ID is equal to the pattern number
            if(parseInt($(obj).attr("id")) === parseInt(list[i])){

                $(obj).css("opacity","1");
                setTimeout(function(){
                    $(obj).css("opacity",".5");
                }, 500);
            }
        })
        i++;
        if( i < list.length){
            showPattern();
        }

    },3000);
}


Solution

  • With hoisting, only the declaration part of the statement var i = 0 (var i) gets hoisted. The i = 0 part does not. So, when your code (without list) runs and encounters:

    list[i]
    

    i is undefined. However, when you pass list and then hit the line:

    list[0] + i
    

    The + symbol implicitly converts i to a default type that is compatible with list[0] (string or number).