In the following Java snippet, the scope of i is limited to the inside of the for loop. That’s why it causes an error. However, in the similar JS snippet, the i is apparently accessible outside of the loop. How is that possible?
Java:
for(int i=0;i<10;i++) {
...
}
System.out.println(i);
Output: “i is not defined”
JS:
for(var i=0;i<10;i++) {
...
}
console.log(i);
Output: 10
I didn’t expect to see output from the JS. I want to know how JS differs from Java. How does JavaScript variable scope work?
In Javascript “local” variables have function scope, not block scope.
All local variable declarations are “hoisted” to the top of the current scope, so your code is equivalent to:
Note that while the declaration is hoisted, any assignment is not. e.g. this code
is equivalent to: