Truthy and Falsy Values in JavaScript

Photo by Joan Gamell on Unsplash

Truthy and Falsy Values in JavaScript

In JavaScript, There are 6 falsy values and these are - 0(Zero), ' ' (Empty String), Undefined, Null, NAN, and False.

Falsy values are not exactly false initially but will become false when we try to convert them to boolean.

console.log(Boolean(null)); //false
console.log(Boolean(undefined)); //false
console.log(Boolean('')); //false
console.log(Boolean(0)); //false
console.log(Boolean(false)); //false
console.log(Boolean(NaN)); //false

All other values are truthy values except which are mentioned above. Any number which is non-zero, and any string which is not empty will return true when we will convert them to boolean.

NOTE: An empty object is a Truthy Value.

let a = {}; //creating empty object
console.log(Boolean(a)); //true 
console.log(Boolean('P')); //true
console.log(Boolean(8)); //true

In most situations, we do not need to type conversion to Boolean, It happens internally by JavaScript as type coercion when need in case of if-else and logical operators.

let money; // undefined
if(money) // condition will return false
    console.log('Money is defined');
else
    console.log('Money is not defined');
//Output - Money is not defined
//As there is no value assigned to money, It is undefined initially and when checked in if condition, JavaScript converts it boolean and takes the decision