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

Viewed 43852

Consider the following:

(function(){
   var foo = bar = 1;
}());
  • foo will be a local variable to the function
  • bar will be a global variable to the window

Due to their scoping, both variables will have a value of 1 inside the function, but bar will persist outside the function (in global scope).

I'm curious if there is a way to initialize variables using the assignment operator, without a loop or an object. I'm looking for a keyword or prefix that would make bar locally scoped. The idea is to be DRY and efficient.


Edit: The example above is simple. One option, using 10 variables, might be to predeclare the variable to the local scope before initializing it:

var foo, bar, baz, foobar, foobaz, bazfoo, barbaz,
    bazbar = foo = bar = baz = foobar = foobaz = barbaz = true;

However, doing so is both repetitive and harder to read. A person could use an array or object, but that is a little less clear and more cluttered.

The background was that another developer was doing var foo = bar = true inside a function, which I pointed out is only setting one local variable. They were not aware of that and wanted to change and asked if it's possible to inline and set multiple local variables, without typing each one multiple times (and not refactor code w/ array or object).

Upon originally asking this question, I was exposed to ES6, but had yet to fully read the docs. My thinking was that ES6 has some nice features (e.g., rest, destructuring assignment) and so perhaps it also provided a way to massively initialize a large block of variables to the same scope and value.

3 Answers
Related