james
james

Reputation: 4049

Javascript equals "0" returning true

Can someone explain this behavior:

"2"=="3"=="4"=="5"
>false
"2"=="3"=="4"=="0"
>true

Just noticed it in console, I would expect both statements to be false. I notice that the true return seems to be an issue when only the LAST value is "0". It's a string comparison though so I'm not sure why this is happening.

Upvotes: 2

Views: 182

Answers (6)

Pichet Jiranarumit
Pichet Jiranarumit

Reputation: 186

Because this case "==" compare number values instead of boolean values
Step 1 : "2"=="3" //"2" == "3" ? Return false
Step 2 : Number(false)==Number("4") //0 == 4 ? Return false
Step 3 : Number(false)==Number("0") //0 == 0 ? Return true

try this: console.log("A"=="A"==1)
Step 1 : "A"=="A" //"A" == "A" ? Return True
Step 2 : Number(true) == 1  // 1 == 1 ? Return true;

Upvotes: 0

Tanvir Ahmad Shaikh
Tanvir Ahmad Shaikh

Reputation: 11

In javascript false evaluates to 0 i:e zero.

So when you do "2"=="3" the answer is 0

0=="4" again is false i:e 0

0=="5" again evaluates to false. Hence the Answer to "2"=="3"=="4"=="5" is false.

And in your second statement "2"=="3"=="4"=="0" "2"=="3"=="4" evaluates to false.

And false == 0 evaluates to true. Hence the answer of "2"=="3"=="4"=="0" is false=="0" i:e true.

Hope that explanation helps.

Have a good day !

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

JavaScript evaluates left-to-right.

Your equations are essentially (("2"=="3")=="4")=="5" and (("2"=="3")=="4")=="0".

Breaking down equation #1:

"2" == "3" // false
false == "4" // false
false == "5" // false

Thus the first equation evaluates to false.

Breaking down equation #2:

"2" == "3" // false
false == "4" // false
false == "0" // true

Thus the second equation evaluates to true. This is due to truthiness equating "0" as false.

If you were to use === (checking for strict equality), the second equation would evaluate to true.

Upvotes: 2

sumit
sumit

Reputation: 15464

JavaScript always evaluates expressions from left to right order. For expression a=b+c/d a is evaluated and then b,c,d

console.log("2"=="3"=="4"=="5"); //false
 /* 
    1. First it will evaluate "2"=="3" as false 
    2. false=="4"=="5" Then it will evaluate false=="4" as false
    3. then false=="5" is false again 
 */
console.log("2"=="3"=="4"=="0"); //true
/* 
    1. First it will evaluate 2==3 as false 
    2. false=="4"=="0" Then it will evaluate false=="4" as false
    3. then false=="0" is true , because 0 is false 
 */

Upvotes: 0

York Chen
York Chen

Reputation: 754

step1: "2"=="3"=="4"=="5"
step2: false=="4"=="5"
step3: false=="5"
step4: false

step1: "2"=="3"=="4"=="0"
step2: false=="4"=="0"
step3: false=="0"
step4: true

Upvotes: 0

Nick
Nick

Reputation: 16576

The second one eventually evaluates to false == "0". Since Since 0 is falsey, this evaluates to true.

console.log(false == "0");

Upvotes: 2

Related Questions