Consider the following:
var x = "outer scope";
(function() {
alert(x);
var x = "inner scope";
})()
Do you think that alert will output "outer scope"? No! It will happen only if you uncomment inner
var x
. But how the code written
after the statement can affect it? Yes, it can. JavaScript is a very non-trivial thing; it is said to be the most misunderstood language in the world. The second
var
declaration tells the interpreter to use inner scope, which makes
x
on previous line
undefined
. So, JavaScript is not the interpreter which merely interprets and executes everything line by line.
The
var
keyword is used to resolve scope. Moreover, in JavaScript
strict mode it is considered,
var
is made a must. And new
let
keyword introduced in in v.1.7 acts differently; if you used
let
instead of
var
in the function I show, it would generate an error. Unlike
var
,
let
is sensitive to the lexical scope.
All these features are the part of effort to introduce better support of JavaScript programming activity, to make it more reliable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var[
^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode[
^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let[
^].
—SA