How to set multiple local variables to the same value in a single declaration?

You can't (or shouldn't) assign a value to an undeclared variable.

Then, when you want to declare multiple variable with the same value, you can

  • Assign the same value to each variable:

    var var1 = value,
        var2 = value,
        /* ... */
        varN = value;
    

    In case value is an expensive expression, you can use var1 instead of repeating value to avoid recalculating it each time, e.g.

    var foo = 1, bar = foo;
    
  • Declare all variables first, and then assign the values to all of them:

    var var1, var2, /* ..., */ varN;
    var1 = var2 = /* ... = */ varN = value;
    

    You can do it in a single statement and avoid repeating the last variable, e.g.

    var foo, bar = foo = 1;
    
  • If you really want to avoid repeating the variables and the values, you could try a destructuring assignment with [].fill:

    var [var1, /*...*/ varN] = new Array(n).fill(value);
    

    But I don't recommend it because it will create an useless array.


It's not very nice, but here's an interesting option that's sort-of DRY:

(function(){
  with ({_: 1}) var x = _, y = _;
}());

The with statement creates a de-facto temporary _ variable, which we apply only to our var statement to ensure there are no other side effects. This does repeat _, but avoids repeating anything meaningful. However, this is a terrible choice because (a) it kills the optimizer by using with, (b) it's not supported in strict mode due to using with, and (c) it relies on var's scope semantics, which we're all trying to get away from by using let and const from now on.

I suppose we could use this more coherent ES6 equivalent.

(function(){
  { let _ = 1; var x = _, y = _; }
}());

However, I feel even more wrong to be taking advantage of var and let's different semantics in the same line.

Let's forget we ever had this train of thought.


If you want to declare two variables and initialize them using a single expression inside of a single statement, the only reasonable syntactic option the following. There is no option that avoids repeating the variable name without involving an additional variable or object.

(function(){
  var bar, foo = bar = 1;
}());

It works, but it's incompatible with the ES6 const keyword, because bar isn't being assigned by the declaration (const bar), but by a sub-expression (bar = 1). There's no supported way to accomplish this with const as a single statement.

(function(){
  const bar, foo = bar = 1;
}());
Uncaught SyntaxError: Missing initializer in const declaration

The multi-line version obviously has no such issue. For what it's worth, I also find it easier to read.

(function(){
  const foo = 1;
  const bar = foo;
}());

Tags:

Javascript