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);
}
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);
}
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
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 ===.
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)
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);
}