1

Probably I am confused or something but I am not able to understand this silly scenario.

if("true"){
  console.log("Above is true");
}
else{
  console.log("Above is false");
}

In the above case the console is nicely printing Above is true. Which makes total sense. But when I am doing:

if("true" == true){
  console.log("Above is true");
}
else{
  console.log("Above is false");
}

I am seeing that Above is false is getting printed in the console.

I am using a loose equality operator here and even after coercion true will convert to "true" so it should print Above is true but is not. What am I missing?

void
  • 36,090
  • 8
  • 62
  • 107

2 Answers2

4

check out this article https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

//EQUALITY CHECK...
"true" == true; 
//HOW IT WORKS...
//boolean is converted using toNumber
"true" == 1;
//string is converted using toNumber
NaN == 1; //false!
user3666653
  • 188
  • 1
  • 7
  • `//string is converted using toNumber` - Nope... -> [11.9.3.7](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) (11.9.3.5 is not fulfilled) – Andreas Mar 03 '18 at 09:00
0

"If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false."

true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true

Further readings on here.