-2

I am stumped as to why the below console.log is not called based on the code below. x certainly does not equal '' since it is set to 0

var x=0;

if (x!=''){
  console.log('here', x);
}
Igor
  • 60,821
  • 10
  • 100
  • 175
tbdevmanager
  • 373
  • 5
  • 15

4 Answers4

0

You need to use !== instead of !=

var x = 0;

if (x !== ''){
  console.log('here', x);
}

Same goes for === instead of ==

This is because the triple equals checks the type as well, otherwise the values get coerced into being "truthy" or "falsey" values.

console.log(0 == '');   //>true
console.log(0 === '');  //>false
console.log(3 == '3');  //>true
console.log(3 === '3'); //>false
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
0

Here's a pretty good article explaining "truthiness" and "falsiness" in JavaScript:

https://j11y.io/javascript/truthy-falsey/

To get around it, use strict comparisons, !== and ===.

Aaron Gates
  • 469
  • 4
  • 15
0

This is because 0 is a falsy value (https://developer.mozilla.org/en-US/docs/Glossary/Falsy)

if (0) console.log("hi, I'm a falsy value)

if you want to check the exact type and value try === operator

if (x === 0) console.log("zero here)
0

This is because you are using Loose Equality

Loose equality compares two values for equality, after converting both values to a common type. After conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it.

The == converts both the operands to common type. Here 0 is Number so it will convert '' to Number using Number('') And Number('') returns 0 so thats why 0 == ''.
If you want to avoid this you may use === and !==

console.log(Number(''))//0

var x = 0;
if (x !== ''){
  console.log('here', x);
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73