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,233
  • 5
  • 42
  • 94

3 Answers3

5

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
  • 2,009
  • 14
  • 20
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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 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
  • 8,132
  • 2
  • 38
  • 47