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
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;
Yup - don't mix declarations and assignments.
var x, y;
x = y = 14;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With