Double compare in JavaScript looks weird

77 views Asked by At

Let's var a = "first", b = "second", c = "first";.
Expression a == c returns true, (of course!); a == c is true too.
Then why does a == a == c return false?

Example

var a = "first", b = "second", c = "first";

write( a != b != c );
write( a == b != c );
write( a == b == c );
write( a != b == c );
write("");
write( a == a == c );

// -------------------
function write(val) {document.querySelector("console").innerHTML += "<hr noshade size='1px' color='#eee'>" + String(val);}
<console></console>

3

There are 3 answers

1
gilly3 On BEST ANSWER

Because what is really happening is this:

(a == a) == c

Which is really just:

true == "first"

See Operator Precedence.

0
SLaks On

a == c returns a boolean (true).

Since a is not a boolean, it cannot possibly equal a == c.

0
Petr Skocik On

Because it goes from left to right, one == at a time and the result of each previous == operation is a boolean:

(a == a) === true
(true == c) === false

You need to do:

a == a && a == c

or better yet (since this is JavaScript):

a === a && a === c

Alternatively, can write in CoffeeScript, which will translate:

a == a == c

into

(a === a && a === c);

for you.