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';
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';
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');
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).
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 anInitializer
the variable is assigned the valueundefined
when the LexicalBinding is evaluated.