1
(function(){
    var b1 = b2 = b3 = b4 = 100;
})();

console.log(b1); //100
console.log(b2); //100
console.log(b3); //100
console.log(b4); //100

Here assignment is right associative and hence 100 is assigned.

It is a bad practice. Better version is

(function(){
  'use strict';
   var b1 = 100,
   b2 = 100,
   b3 = 100,
   b4 = 100;
})();

Question: Is there any case where such wrong assignment

var b1 = b2 = b3 = b4 = 100; 

could be preferred or should it never be used?

7
  • 1
    I think your time would be better spent analyzing problems which require solutions. Commented Jan 9, 2015 at 0:23
  • Bad practice, my ass. If you have four values that are intended to be equal, chained assignment is the single most reliable way to do it. Though you do want the variables to exist first. Commented Jan 9, 2015 at 0:23
  • 2
    @Mathletics it's definitely not "opinion-based". The var statement only declares the variable to the left of the first (left-most) = sign. The rest are implicit global references. Commented Jan 9, 2015 at 0:25
  • @cHao I hope you don't really do this, because it's wrong. Commented Jan 9, 2015 at 0:27
  • @Pointy: The way it's being done up there, yeah, it's wrong. But there's absolutely nothing wrong with a = b = c = d = 0;. Commented Jan 9, 2015 at 0:31

1 Answer 1

5

It is not okay, since those 2 code examples are not identical. The first one equals to:

var b1;
b4 = 100;
b3 = b4;
b2 = b3;
b1 = b2;

So you only define b1 in the local scope, the b2..b4 are declared globally. Which means this MUST BE completely avoided.

I also highly doubt console.log(b1); outputs 100 as per your example.

(function(){
    var b1 = b2 = b3 = b4 = 100;
})();

console.log(b1); //100 <-- this is not true
console.log(b2); //100
console.log(b3); //100
console.log(b4); //100

From the other hand - for already declared variables - initialization or assignment using

// we assume a, b and c have been declared already
a = b = c = 100;

is a subject of your project/team conventions. From technical perspective it's fine to use it.

Sign up to request clarification or add additional context in comments.

10 Comments

You're mostly right but there's no reason to expect that b1 won't end up with the right value, is there?
On the initial portion of the answer, I say, "Precisely!" On the second part, I don't think that's correct.
@zerkms - I see, you meant with the IIFE context there. Yes, I will retract you are correct.
@zerkms oh durr. Like I said, I don't trust my judgement :)
Actually, @zerkms is completely right. I failed to take into account the location of the calls to console.log in the OP.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.