Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript loop variable scope

Just a quick question about the scoping of JavaScript variables.

Why does the alert() function print the value of i instead of returning undefined?

$(document).ready(function () {     for(var i = 0; i < 10; i += 1){     }       alert("What is 'i'? " + i); }); 

I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?

i.e. What is 'i'? 10' is printed.

like image 329
BlackBox Avatar asked Aug 27 '13 12:08

BlackBox


People also ask

What is the scope of a loop variable?

In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.

What is loop scope in JavaScript?

Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded. Follow this answer to receive notifications.

Should I use VAR or let in for loop JavaScript?

You can see the same behavior while using let if you've already declared the variable before using it in your for loop. Now it would behave the same way as the var for loop did. var is function scoped (in layman terms globally scoped) i.e. value declared using var is available throughout the program.

Why do we use let in for loop?

According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block.


1 Answers

See the MDN for the "initialization parameters" of a for-loop:

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

like image 81
insertusernamehere Avatar answered Sep 19 '22 03:09

insertusernamehere