4

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?

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
  • 1
    [Simple Google search: site:stackoverflow.com javascript a === b === c](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+a+%3D%3D%3D+b+%3D%3D%3D+c) –  Aug 21 '16 at 13:50
  • Sorry @squint, I didn't notice. I was kind of amazed it didn't throw an error that I just wanted to share it with someone :P – Angel Politis Aug 21 '16 at 13:51

2 Answers2

10

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Aha, I knew I was missing something. Thanks @Pointy – Angel Politis Aug 21 '16 at 13:46
  • 4
    Whoa, 9 upvotes in 3 minutes, with the blatant duplicate mentioned in the "related questions" sidebar… – Bergi Aug 21 '16 at 13:50
  • 1
    @Bergi I guess people are bored? Or maybe I'm magic. – Pointy Aug 21 '16 at 13:53
  • @Bergi I did look for a duplicate but I don't understand SO search so I'm bad at it. – Pointy Aug 21 '16 at 13:54
  • @Pointy: I guess you're magic :-) But yes, search is weird, especially that "search", "duplicate search" and "related" seems to use different algorithms that bring up results of very different relevance. And then, as squint mentions, there's Google, which finds some altogether different things. – Bergi Aug 21 '16 at 14:05
6

This is due to how operators are evaluated. In JavaScript, equality operators are evaluated left-to-right (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)

This means that this:

a === b === 0

Becomes this after one step:

true === 0

Since the number zero is not equal to the boolean true, your expression returns false.

pwagner
  • 1,224
  • 1
  • 13
  • 31
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40