Truthiness Check in Javascript

On the way become backend developer
Concept
Using if/else statement is always related to boolean, whether it is true or false. This checking may be called a truthiness check. In Javascript if/else statement not always about boolean data type but also behavior. Variables might have the same behavior astrue or false but not a boolean data type.
In if/else statement, we may state our code like this one:
// condition checking in if statement
if (condition){
// condition is true
}
// condition checking in if/else statement
if (condition){
// condition is true
} else{
// condition is not true
}
In if/else statement, the condition may check whether it is identical or equal or just acting like.
Identical means that it has the same value/behavior and the same data type. If those requirements are fulfilled then it returns to be true. On the other side, equal only means it has the same value/behavior as a true or false. So the if/else statement may act like below:
if (condition == true){
// condition is true
}
if (condition === true){
// condition is a boolean with a true value
}else {
// condition is not boolean or does not have the true value
}
Different with acting like, we will learn in case.
Cheatsheet
Now let's check code below:
// Below will have the same behavior as false
var isUndefined = undefined;
var isNull = null;
var isZero = 0;
var isZeroFloat = 0.0;
var isEmptyString = "";
All those variables will have the same behavior as false but not identical or equal to false. This is a little bit strange and confusing, so let's take an example. Now we check the undefined variable.
// undefined have the same behavior as false
if (!isUndefined){
console.log('isUndefined act as false'); // This log will show
}
// undefined is not equal to false
if (isUndefined == false){
console.log('isUndefined is not equal to false'); // This log will show
}
// but undefined is not identical to a boolean in a strict comparison even it
// have same value/behavior as false
if (isUndefined === false){
console.log('isUndefined is not same with false'); // this log won't show
}
See, in the first if condition, undefined act like false but if we check if undefined is equal to false, the result is not. To better understand, I resume those variable results in the table below.
| Variable | Behavior like false | Equal to false | Identical to false |
| isUndefined | Yes | No | No |
| isNull | Yes | No | No |
| isZero | Yes | Yes | No |
| isZeroFloat | Yes | Yes | No |
| isEmptyString | Yes | Yes | No |
Look how different data types have different conditional results in Javascript.
If you curious about javascript strange behavior, you could visit JavascriptWTF.


