Consider the following for loop in Javascript.
for( var i=0;i<10;i++){ }
console.log(i);
If i run the code, I will get 10 in the console. Why is this? How is the scope of variable 'i' available outside for loop ?
Consider the following for loop in Javascript.
for( var i=0;i<10;i++){ }
console.log(i);
If i run the code, I will get 10 in the console. Why is this? How is the scope of variable 'i' available outside for loop ?
In javascript, there is no block level scope prior to ES6 (with let), so any variable you declare will have a function level scope (if the declaration is inside a function) or global scope.
JavaScript before ECMAScript 6 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.