1

In javascript, a (admittedly sloppy) way of checking whether a variable is set is to check whether it's "truthy", by

var blah;

blah = "foo"; // in real code, this assignment might happen only sometimes

if(blah) {
  console.log('blah is set'); 
}

I had thought "loose" equality operator was equivalent to a truthy test. Howcome, then, the expression "foo" == true evaluates to false?

aaaidan
  • 7,093
  • 8
  • 66
  • 102

1 Answers1

1

if( expression ) checks for truthiness while x == y uses conversions to determine equality. It's not exactly the same concept.

The conversions are detailed on MDN. For ==:

If the two operands are not of the same type, JavaScript converts the operands, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Based on this, "foo" == true is equivalent to NaN === 1 and is false.

dee-see
  • 23,668
  • 5
  • 58
  • 91