6

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 ?

  • possible duplicate of [Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)](http://stackoverflow.com/questions/7581439/is-setting-multiple-variables-in-1-line-valid-in-javascript-var-x-y-value) –  Jul 15 '15 at 13:21
  • 1
    Its not a question related to possibilities for `initialization of several variables` but with variable `Scope` changes @torazaburo. – ANR Upgraded Version Jul 15 '15 at 16:01
  • Read the proposed duplicate more closely. –  Jul 15 '15 at 16:13

1 Answers1

7

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;
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Actually, the original code is equivalent to `y=1; var x=1;`. If `y` couldn't be assigned to 1 for whatever reason, `x` would still equal 1. See http://stackoverflow.com/a/31414927/3903374 – Rick Hitchcock Jul 15 '15 at 11:21
  • @RickHitchcock More precisely, it's the value of the (y=1) expression. Saying it's 1 is equivalent in that case to saying it's y. – Denys Séguret Jul 15 '15 at 11:24
  • 1
    Correct in this instance, but that was the assumption in my linked post, which was incorrect in that instance. If `y` were previously declared as a `const` 2, `x` would *not* equal 2. – Rick Hitchcock Jul 15 '15 at 11:31