Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"use strict": Assign Value to Multiple Variables

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

like image 325
Vainglory07 Avatar asked May 05 '15 03:05

Vainglory07


2 Answers

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;
like image 188
sfletche Avatar answered Oct 04 '22 18:10

sfletche


Yup - don't mix declarations and assignments.

var x, y;
x = y = 14;
like image 22
Niet the Dark Absol Avatar answered Oct 04 '22 20:10

Niet the Dark Absol