How to Check if a Value is Truthy in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

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 executes the if block.

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

In our if statement, we check if the value in the myVar variable is truthy. Truthy are all values that are not falsy.

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

Our if block would run if myVar stores any other value than the aforementioned.

Truthy values in an if statement get coerced to true before the if block gets executed. 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 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 }

In the example, we basically check if the array contains at least 1 element and the object 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 }

Here, 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 statement executes.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee