0

My code basically looks like this:

console.log(placeCost) //this returns 0 (the number, not string)
 if (!placeCost || placeCost == false || placeCost == "undefined" || placeCost == '') {
 console.log("no")
             }
else {console.log('yes')}

Results is "no" in the console. Why does this resolve as "true"?

jonmrich
  • 4,103
  • 5
  • 37
  • 87

3 Answers3

4

Try using the === operator and don't check for !var if you plan to accept falsy parameters. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

if (placeCost === false || placeCost === "undefined" || placeCost === '') {
    console.log("no")
} else {
    console.log('yes')
}
Bellian
  • 1,899
  • 12
  • 19
2

You can refer to comparison operators :

Equality (==)

The equality operator == converts the operands if they are not of the same type, then applies strict comparison.

So !placeCost (like its more verbose form : placeCost == false) is evaluated to true if placeCost is the 0 number as 0 is converted to the false value.

You want do a strict comparison ?
Use === that performs no conversion :

The identity operator returns true if the operands are strictly equal (see above) with no type conversion.

davidxxx
  • 115,998
  • 20
  • 192
  • 199
  • for reference: https://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript – AJ X. Sep 01 '17 at 14:01
0

if placeCost is 0 then !placeCost become 1, that will leads the condition is true.

if (!placeCost) // condition true when placeCost is 0
Deepu Reghunath
  • 6,468
  • 1
  • 30
  • 41