2

In the following example, is a new variable 'y' created for each iteration through the for..in loop? Or is the variable declaration hoisted to the top of the function, and re-used for each iteration?

function example() {
    var x;
    for(x in obj) {
       var y = obj[x];
    } 
}

Thanks

3 Answers 3

3

It's hoisted, since the for loop has no effect on scope.

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

1 Comment

I figured, just wanted to make sure. Thanks.
0

y is the same variable being replaced. to make a new one you would use

function example() {
    var x;
    var y= new Array;
    for(x in obj) {
       y[x] = obj[x];
    } 
}

4 Comments

I'm afraid that's not right. If you break your loop into two statements: var y and y[x] = obj[x], and then read the value of y between those two statements, you'll find that y still contains the array. Ie, it is not a new undefined variable.
y is supposed to still contain the obj array item, but now y can index each item from the obj array. i beleive he was asking if y will hold only the last item in the obj array. which is correct, by using y[x] y will contain the same array as obj.
Then why use the var keyword?
my mistake. i didnt realize y was defined already when i copied his code var y[x] = obj[x];
0

You can test this for yourself:

var obj = {
  name: "Dan",
  surname: "Tao"
};

var x;
for (x in obj) {
  var y = obj[x];
}
alert(y);

An alert box will appear with the text Tao, indicating that y is accessible outside the scope of the for loop.

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.