Friday, May 9, 2014

javascript does not have block scope

Javascript has two types of scope. Global scope and local scope.
Global scope is the outermost scope and variables, functions and objects defined at this level are available to any code int the entire program.
Local scope is the scope for each function.

Javascript does not have block scope like many other languages.
For example, the code below console.log(bar) will output 222, although it is declared inside the if block.
Another example here
But javascript does have function scope, the code below would get "Uncaught ReferenceError: bar1 is not defined"
You have to have the "var" in line 2, otherwise a global variable is declared, then the output is going to be "abc".
Using let to attach a variable to an existing block, let will be supported in ECMAScript 6, the next generation javascript
Variable is redefined inside the function, even if it is not executed.

The variable myVar is declared in the if statement, but it’s visible from outside the block because javascript does not have block scope. Javascript has global scope and function scope. It is different with other languages.

Another example here
Use "let" (ES6) can avoid this issue

No comments:

Post a Comment