Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Initialization of several variables leading into Scope Leakage?

I was referring docs of JavaScript var hoisting , There in a section i found Initialization of several variables with a Example given below.

var x = 0;

function f(){
  var x = y = 1; 
}
f();

console.log(x, y); // outputs 0, 1
// x is the global one as expected
// y leaked outside of the function, though! 

Where I Suppose to get Exception as Uncaught Reference Error: y is not defined. but it is not happening due to leaked Scope and it is displaying 0,1.

Can I Know why it is happening in detail and what made this to happen. Finally any performance related issues ?

like image 805
ANR Upgraded Version Avatar asked Jul 15 '15 11:07

ANR Upgraded Version


1 Answers

You're not declaring y.

var x = y = 1; 

is equivalent to

y = 1;
var x = y; // actually, the right part is precisely the result of the assignement

An undeclared variable is a global variable (unless you're in strict mode, then it's an error).

The example you're referring to was different, there was a comma, which is part of the multiple declaration syntax.

You could fix your code in

var y=1, x=y;
like image 102
Denys Séguret Avatar answered Nov 07 '22 01:11

Denys Séguret