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

1
  • Yes, this does successfully set multiple variables. But it does only declare x Commented May 5, 2015 at 3:14

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

9 Comments

The last example still makes y global, does it not?
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.
You are correct. Thanks @FelixKling. Edited my answer to reflect your correction.
I was wrong. You were correct that it is var x = 14; (because y = 14) results in 14.
@FelixKling If you want to get specific, it's equivalent to var x; y = 14; x = y; :D
|
7

Yup - don't mix declarations and assignments.

var x, y;
x = y = 14;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.