Javascript How to define multiple variables on a single line?

Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.

If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?

var a = 0;
var b = 0;

Is it:

var a = b = 0;


var a = var b = 0; 




You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.

An example would be:

>>> var a = b = c = [];
>>> c.push(1)
>>> a

They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.

There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.

(function() {  var a = global = 5 })();
alert( // 5

It's best to just use commas and preferably with lots of whitespace so it's readable:

var a = 5
  , b = 2
  , c = 3
  , d = {}
  , e = [];

Using Javascript's es6 or node, you can do the following:

var [a,b,c,d] = [0,1,2,3]

And if you want to easily print multiple variables in a single line, just do this:

console.log(a, b, c, d)

0 1 2 3

This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.

Note that this uses Javascript's array destructuring assignment


There is no way to do it in one line with assignment as value.

var a = b = 0;

makes b global. A correct way (without leaking variables) is the slightly longer:

var a = 0, b = a;

which is useful in the case:

var a = <someLargeExpressionHere>, b = a, c = a, d = a;

Why not doing it in two lines?

var a, b, c, d;    //All in the same scope
a = b = c = d = 1; // Set value to all.

The reason why, is to preserve the local scope on variable declarations, as this:

var a = b = c = d = 1;

will lead to the implicit declarations of b, c and d on the window scope.


Here is the new ES6 method of declaration multiple variables in one line:

const person = { name: 'Prince', age: 22, id: 1 };

let {name, age, id} = person;


* Your variable name and object index need be same


Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:

let [a, b, c, d] = Array(4).fill(0);

console.log(a, b, c, d);


note you can only do this with Numbers and Strings

you could do...

var a, b, c; a = b = c = 0; //but why?

// c = 1, b = 0, a = 0;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.