Java vs. JavaScript variable scope [closed]

蓝咒 提交于 2019-12-24 21:19:58

问题


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?


回答1:


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
}



回答2:


Javascript only has two types of scoping - global and functional. Javascript is lexically scoped at the function-level.



来源:https://stackoverflow.com/questions/12645073/java-vs-javascript-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!