This question already has an answer here:
-
Multiple left-hand assignment with JavaScript
7 answers
Is there any way to assign two variables to the same value?
Just tried this:
let x, y = 'hi'
and it's compiling to this:
'use strict';
var x = void 0,
y = 'hi';
There is absolutely no reason to prefer the destructuring assignment over simply
let x = 'hi', y = x;
Not only it's one statement instead of two, but it also avoids extra allocations (the provided solution with destructuring allocates at least one object with no good reason).
Yes, it is possible:
let x, y;
x = y = 'hi';
It is called chaining assignment, making possible to assign a single value to multiple variables.
See more details about assignment operator.
If you have more than 2 variables, it's possible to use the array destructing assignment:
let [w, x, y, z] = Array(4).fill('hi');
You can do this way .. But my suggest try to avoid it.
var one, two, three;
one = two = three = "";
That's expected behavior. From the EMCA-262 6th edition:
If a LexicalBinding in a let
declaration does not have an
Initializer
the variable is assigned the value undefined
when the
LexicalBinding is evaluated.
var x = y = 'hi';
alert('x'+x);
alert('y'+y);
Fiddle