Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the function return false? [duplicate]

Tags:

javascript

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?

like image 711
Angel Politis Avatar asked Dec 05 '22 00:12

Angel Politis


2 Answers

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.

like image 65
Pointy Avatar answered Dec 24 '22 01:12

Pointy


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.

like image 39
Robert Columbia Avatar answered Dec 23 '22 23:12

Robert Columbia