2

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
  • 1
    If you only want to process the even rows, why don't you do row_i += 2 instead of checking whether it's even each time? Commented Oct 2, 2020 at 0:44

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.