Ad

Java Vs. JavaScript Variable Scope

- 1 answer

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?

Ad

Answer

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:

var i;
for (i = 0; i < 10; ++i) {
}
console.log(i);

Note that while the declaration is hoisted, any assignment is not. e.g. this code

function test() {
    console.log(i);  // undefined
    var i = 1;       // declaration and assignment
    console.log(i);  // 1
}

is equivalent to:

function test() {
    var i;           // declaration hoisted
    console.log(i);  // undefined
    i = 1;           // assignment still happens here
    console.log(i);  // 1
}
Ad
source: stackoverflow.com
Ad