How to Check if a Value is Truthy in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Check if a Value is Truthy in JavaScript #

To check if a value is truthy, pass the value to an if statement, e.g. if (myValue). If the value is truthy, it gets coerced to true and the if block runs.

index.js
const myVar = 'test'; if (myVar) { console.log('✅ myVar is truthy'); } else { console.log('⛔️ myVar is falsy'); }

The if statement checks if the value stored in the variable is truthy. Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, 0, empty string, null, undefined, NaN.

The if block only runs if the variable stores any other than the aforementioned falsy values.

Truthy values in an if statement get coerced to true before the if block is run. Here are some examples of truthy values used in an if condition.

index.js
if ([]) { console.log('✅ This runs'); } if ({}) { console.log('✅ This runs'); } if (true) { console.log('✅ This runs'); } if ('test') { console.log('✅ This runs'); }

Note that an empty array and an empty object are considered truthy, whereas an empty string is considered falsy.

index.js
if ('') { console.log("⛔️ this doesn't run"); }

If you need to check if an array or object contains elements or key-value pairs, do this instead:

index.js
if (['a'].length > 0) { // 👉️ array is not empty } if (Object.keys({a: 'b'}).length > 0) { // 👉️ object is not empty }

We check if the array contains at least 1 element and whether the object contains at least 1 key-value pair.

You could also do the check implicitly, e.g.:

index.js
if (['a'].length) { // 👉️ if this runs, the array is not empty }

We implicitly check for the length of the array. If the array is empty, its length property will return 0, which is a falsy value, and our if block wouldn't run.

If the array contains at least 1 element, the length property would return a positive integer, which is a truthy value. The value gets coerced to true and the if block runs.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.