4

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';
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

5 Answers5

7

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');
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
7

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).

zerkms
  • 249,484
  • 69
  • 436
  • 539
1

You can do this way .. But my suggest try to avoid it.

var one, two, three;
one = two = three = "";
  • JS by itself doesn't use explicitly defined types such as string. – Satej S May 09 '16 at 05:20
  • Why should I avoid it? –  May 09 '16 at 05:53
  • @torazaburo because it's a strong positive sign that you're doing something wrong. Just create one variable, not 3 with the same data. – zerkms May 09 '16 at 05:58
  • Huh? What if I have two or three distinct variables, that I happen to want to initialize to the same value? –  May 09 '16 at 06:30
  • @torazaburo I don't remember last time I did that. Any chance you can make of an algorithm/a task where it's the mandatory implementation detail? – zerkms May 09 '16 at 07:13
  • 1
    I don't really care, and it's a semi-stupid question, but yes, I can easily imagine cases where I have two counters, let's say, and want to initialize them both to zero. However, I see no reason not to just say `var x=0, y=0;`. –  May 09 '16 at 16:05
0

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.

-2
var x = y = 'hi';
alert('x'+x);
alert('y'+y);

Fiddle

Imad
  • 7,126
  • 12
  • 55
  • 112