7

Is there any other way in "use strict"; javascript to initialize a value to multiple variables? Because doing this:

var x = y = 14;

will cause error: Uncaught ReferenceError: y is not defined

Got my reference here:

Set multiple variables to the same value in Javascript

Community
  • 1
  • 1
Vainglory07
  • 5,073
  • 10
  • 43
  • 77

2 Answers2

21

There are side affects to var x = y = 14; which is why it's not allowed in strict mode. Namely, y becomes a global variable.

When you say

var x = y = 14;

It is equivalent to

var x;
y = 14;
x = y;

Where x is declared as a local variable and y is created as a global variable.

For more information on using var to declare variables see this question. Additionally, it may be worth noting that ES6 is introducing the keyword let that enables block level scoping in contrast to function level scoping that exists with var.

Finally, if you want to assign both variables a value, any of the following would do

var x, y;
x = y = 14;

var x = 14,
    y = x;

var x = 14,
    y = 14;

var x = 14;
var y = 14;
Community
  • 1
  • 1
sfletche
  • 47,248
  • 30
  • 103
  • 119
  • The last example still makes `y` global, does it not? – Niet the Dark Absol May 05 '15 at 03:11
  • Actually, `var x = y = 14;` is equivalent to `y = 14; var x = 14;`. But I guess the order is not very important. In that case. – Felix Kling May 05 '15 at 03:13
  • You are correct. Thanks @FelixKling. Edited my answer to reflect your correction. – sfletche May 05 '15 at 03:14
  • I was wrong. You were correct that it is `var x = 14;` (because `y = 14`) results in `14`. – Felix Kling May 05 '15 at 03:15
  • @FelixKling If you want to get specific, it's equivalent to `var x; y = 14; x = y;` :D – Niet the Dark Absol May 05 '15 at 03:16
  • @NiettheDarkAbsol: I was considering it, but didn't want to bring in hoisting as well ;) – Felix Kling May 05 '15 at 03:16
  • Thanks to both @FelixKling and @NiettheDarkAbsol for the corrections. I've updated my response to what I think we all believe is the correct equivalent to `var x = y = 14;` – sfletche May 05 '15 at 03:19
  • @sfletche—cool, might be handy to include the link: [*What is the function of the var keyword and when to use it (or omit it)?*](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it). – RobG May 05 '15 at 03:30
  • Nice link @RobG. I included it as well as a link to an explanation for the `let` keyword for additional reading... – sfletche May 05 '15 at 03:39
7

Yup - don't mix declarations and assignments.

var x, y;
x = y = 14;
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592