Ad
Java Vs. JavaScript Variable Scope
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad