Truthiness Check in Javascript

Photo by Alex Shute on Unsplash

Truthiness Check in Javascript

·

3 min read

Table of contents

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.

VariableBehavior like falseEqual to falseIdentical to false
isUndefinedYesNoNo
isNullYesNoNo
isZeroYesYesNo
isZeroFloatYesYesNo
isEmptyStringYesYesNo

Look how different data types have different conditional results in Javascript.

If you curious about javascript strange behavior, you could visit JavascriptWTF.

Did you find this article valuable?

Support Hermansyah by becoming a sponsor. Any amount is appreciated!