+ 1

Don't understand this can anyone help

What is the output of this code? var a = true; var b = "01"; alert(Number(a == b)); i know the results is 1 but why is that ?!

26th Apr 2017, 9:21 PM
Ionut Marian
Ionut Marian - avatar
4 Answers
+ 18
0 is regarded as false, and 1 is true. (a == b) is a condition that returns true or false. Since a = true = 1, and b = "01" = "1", a == b is true. Convert true to a number, and you get 1.
26th Apr 2017, 9:24 PM
Tamra
Tamra - avatar
+ 15
because in Javascript true has the numeric value of 1. in the comparison (a == b) is like you are comparing 1 and '01'. because you use two equals that means compare them without taking in consideration their type the result is true.
26th Apr 2017, 9:28 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
the above answers are perfect, but I'll add in case you didn't know, I believe if you were to use the strict equality (===), it would evaluate as false. JS isn't my favorite, but if I'm not mistaken it works like this... 1 == "1" true 1 === "1" false ...the strict equality is taking into account that one of them is a string and the other is an integer.
28th Apr 2017, 6:26 PM
toddy
toddy - avatar
+ 1
You got some great responses there bud
7th May 2017, 1:09 AM
Philip Lewis
Philip Lewis - avatar