Javascript
use var, always
4번독수리
2016. 11. 21. 17:40
Use var
, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var
statement. If it cannot find a var
then it is global (if you are in a strict mode, using strict
, global variables throw an error). This can lead to problems like the following.
function f (){
for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2
If you write var i
in the for loop the alert shows 2
.
http://stackoverflow.com/a/5717233 “var” or no “var” in JavaScript's “for-in” loop?