Angel Politis Angel Politis - 3 months ago 7
Javascript Question

Why does the function return false?

I'm trying to shorten out the following code:

var a = 0, b = 0;

function() {
return a === 0 && b === 0; // returns 'true'
}


So, I thought something like the following would do:

var a = 0, b = 0;

function() {
return a === b === 0; // returns 'false'
}


Initially, I thought that such syntax would throw an error, but apparently it returns
false
. Why does
a === b === 0
return
false
?

Answer

The expression a === b === 0 is interpreted as if it were written (a === b) === 0. The result is false because (a === b) gives true, and true is not === to 0.

One can imagine a programming language that would understand a chain of expressions connected by == or === or whatever, meaning that all values should be compared in one big "group equality" comparison. JavaScript is not such a language, however.

Comments