JS Can't use array initialized within for loop

Viewed 37

I'm having trouble understanding how scoping works in JS, my background is in R and Python.

This is a toy example. The games_array always prints out as empty at the end. And the array variable doesn't seem to be present in the console.

    for(var row_i = 0; row_i < 50; row_i++){

        var games_array = [];

        if(row_i % 2 == 0){

            console.log(data[row_i].name);
            games_array.push(data[row_i].name);
        }
    }
    console.log(games_array);

But then this works:

    var games_array = [];

    for(var row_i = 0; row_i < 50; row_i++){

        if(row_i % 2 == 0){

            console.log(data[row_i].name);
            games_array.push(data[row_i].name);
        }
    }
    console.log(games_array);

I don't understand why I can't create an empty array and use it within a for loop. I need to wrap this inside an outer loop and use the games_array in the outerloop.

Any help is appreciated.

1 Answers

The problem is not with scoping. After all, since you declared the variable using var instead of let, the scope extends outside of the for loop. The problem is that each time the loop runs, it sets games_array to [], which means the array gets cleared each time the loop runs.

In the second example, you only initialize the array once, which is why it works.

Related