Louis
Louis

Reputation: 1084

cleaner way to assign multi variables

Is there any cleaner way to define multiple javascript variables on a single line?

var a = 0,
    b = 0,
    c = 0,
    d = 0,
    blah = "";

I was wondering if I could write something like this:

var a = b = c = d = 0,
    blah = "";

Upvotes: 2

Views: 145

Answers (3)

Igor Benikov
Igor Benikov

Reputation: 897

Second way get code with side-effects

Try this:

//3 assignments in the 'global' scope
var b = 2,
    c = 3,
    d = 4;

(function(){
    var a = b = 5; //a gets declared in the local scope, 
                   //b get's assigned in the global scope
                   // var a = (b = 5), where (b = 5) returns the value 5 itself
    var d = 5;     //d gets declared in the local scope
}());

console.log(d); //4
console.log(b); //5
console.log(c); //3
console.log(a); //ReferenceError, as a is undefined in this scope

Try to use only the first version to avoid receive surprises

Upvotes: 3

Pointy
Pointy

Reputation: 413826

You can't do this:

var a = b = c = d = 0, blah = "";

because the var syntax is such that it's only the symbol on the left side of the first = that's being declared. You could do this:

var a, b, c, d = 0, blah = "";
a = b = c = d;

edit Further explanation: the first code sample doesn't cause a syntax error (except in "strict" mode), but it doesn't do what it looks like it might do. The variables "b", "c", and "d" are not declared as local variables by such a statement. If they're globals, then the pre-existing value would be overridden. Otherwise, they'd be declared implicitly as globals, not as local variables.

In any case, there's nothing really ugly about declaring and initializing variables one at a time.

Upvotes: 4

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

You could do:

var a, b, c, d, blah = "";
a = b = c = d = 0;

The second way:

var a = b = c = d = 0,  //Wrong!! don't do it
blah = "";

It's wrong because it would declare only a as var and the rest (b, c, d, e) would be globals. Terrible side effect (and hard to detect).

However, I'd stick to the long classic one you showed:

var a = 0, 
    b = 0, 
    c = 0, 
    d = 0, 
    blah = "";

Because it's more standard ;).

Cheers

Upvotes: 3

Related Questions