Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning the variable name to the same variable name

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.

like image 451
vusan Avatar asked Jul 08 '13 07:07

vusan


2 Answers

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!

like image 179
ThiefMaster Avatar answered Oct 14 '22 00:10

ThiefMaster


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

like image 20
rab Avatar answered Oct 14 '22 00:10

rab