Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does (A == B == C) comparison work in JavaScript?

I was expecting the following comparison to give an error:

var A = B = 0;
if(A == B == 0)
    console.log(true);
else
    console.log(false);

but strangely it returns false.

Even more strangely,

console.log((A == B == 1)); 

returns true.

How does this "ternary" kind of comparison work?

like image 631
laggingreflex Avatar asked Apr 10 '14 06:04

laggingreflex


People also ask

What is difference == and === in JavaScript?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.

What is == operator in JavaScript?

The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.

How does JavaScript string comparison work?

The algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second. We're done.

Can you use == to compare strings in JavaScript?

To check if two strings are equal in JavaScript, use equal-to operator == and pass the two strings as operands. The equal-to operator returns a boolean value of true if the two strings are equal, or else, it returns false. Equal-to operator considers the case while comparing the strings.


1 Answers

First, we need to understand that a == comparison between a number and a boolean value will result in internal type conversion of Boolean value to a number (true becomes 1 and false becomes 0)

The expression you have shown is evaluated from left to right. So, first

A == B

is evaluated and the result is true and you are comparing true with 0. Since true becomes 1 during comparison, 1 == 0 evaluates to false. But when you say

console.log((A == B == 1));

A == B is true, which when compared with number, becomes 1 and you are comparing that with 1 again. That is why it prints true.

like image 104
thefourtheye Avatar answered Oct 20 '22 00:10

thefourtheye