for(var i=0;i<5;i++){}
alert(i);
in javascript this will get us 5 other languages like C++, java, c# .... will simply give an error that the i variable isn't defined in the context.
So why the for loop counter doesn't get destroyed after exiting the loop in javascript?
for(var i=0;i<5;i++){}
alert(i);
in javascript this will get us 5 other languages like C++, java, c# .... will simply give an error that the i variable isn't defined in the context.
So why the for loop counter doesn't get destroyed after exiting the loop in javascript?
Share Improve this question asked Jul 4, 2013 at 17:11 ModarModar 856 bronze badges 4- 1 possible duplicate of variable hoisting – Ryan Cavanaugh Commented Jul 4, 2013 at 17:13
- all you need to know stackoverflow./questions/500431/javascript-variable-scope – Manoj Purohit Commented Jul 4, 2013 at 17:14
- read this: Javascript's declaration of variables in a function scope, meaning that variables declared in a function are available anywhere in that function, even before they are assigned a value. – Grijesh Chauhan Commented Jul 4, 2013 at 17:27
- Variable scope: – Grijesh Chauhan Commented Jul 4, 2013 at 20:14
3 Answers
Reset to default 11This is because the JavaScript engine will move ("hoist") the variable decalaration to the top of the function no matter where it is declared inside the function1. JavaScript does not have block scope.
{
//Some code
for(var i=0;i<5;i++){}
alert(i);
//Some code
}
Is equivalent to:
{
var i;
//.. some code
for(i=0;i<5;i++){}
alert(i);
}
1 Unless it's the exception being caught with a catch
clause; that variable is scoped to catch
block.
Update
For defining block scope variables ecmascript 6 specs (javascript 1.7) introduces let. Currently this will work only in latest version of FireFox browser and in consensus stage.
<script type="application/javascript;version=1.7">
//Some code
for (let i = 0; i < 10; i++) {
alert(i); // 1, 2, 3, 4 ... 9
}
alert(i); // Here you will get an error here saying ReferenceError: i is not defined.
}
</script>
Fiddle
Javascript only creates scopes for functions, with
and catch
blocks (with functions creating a scope for var
statement),
so equivalent to Java (and not working) would be:
(function(){
for(var i=0;i<5;i++){}
})();
alert(i);
Variables in Javascript are subjected to var hoisting
where the variable bees declared above the block by the javascript engine.
See The Mozilla Javascript documents on var for an example of how this will work.