On executing
var a=b=c=d=e=f=a;
//no error(a has not initialize before)
var x=y;
//ReferenceError: y is not defined
How can the first code just execute as if a
has already been initialize before.
It's because of variable hoisting. var x = EXPR;
is actually converted to this:
// beginning of the block (function/file)
var x; // === undefined
// ...
// the actual position of the statement
x = EXPR
For your example this means:
var a; // === undefined
a = b = c = d = e = f = a;
Note that only a
is declared using var
- so you are creating tons of globals which is always a bad thing!
Your first statement is like
var a = undefined;
a = window.b = window.c = window.d = window.e = window.f = a;
where a is defined, and others are global scoped . suppose you execute a function .
(function(){
var a=b=c=d=e=f=a;
b = 10;
}());
the b
can accessed outside .
in second var x=y
, y
is not defined yet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With