I can\'t understand why variables act so strange when declared inside a function.
In the first
function I declare with let
the variabl
Before calling things strange, let’s know some basics first:
var and let are both used for variable declaration in JavaScript. For example,
var one = 1;
let two = 2;
Variables can also be declared without using var
or let
. For example,
three = 3;
Now the difference between the above approaches is that:
var
is function scoped
and
let
is block scoped.
while the scope of the variables declared without
var
/let
keyword become global irrespective of where it is declared.Global variables can be accessed from anywhere in the web page (not recommended because globals can be accidentally modified).
Now according to these concepts let's have a look at the code in question:
function first() {
let a = b = c = 10;
/* The above line means:
let a=10; // Block scope
b=10; // Global scope
c=10; // Global scope
*/
var d = 20; // Function scope
second();
}
function second() {
alert(b + ", " + c); // Shows "10, 10" //accessible because of global scope
alert(a); // Error not accessible because block scope has ended
alert(d); // Error not accessible because function scope has ended
}