Check if a Function returns True in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a Function returns True #

To check if a function returns true, call the function and check if its return value is equal to true, e.g. if (func() === true). If the function's return value is equal to true the condition will be satisfied and the if block will run.

index.js
function doWork() { // logic ... return true; } // 👇️ Check if returns explicitly `true` if (doWork() === true) { console.log('✅ function returns true'); }
The only way to check if a function returns true is to call the function and check if its return value is equal to true.

If the condition is met, the if block will be ran.

Alternatively, you can check if a function returns a truthy value.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

index.js
function doWork() { // logic ... return true; } // 👇️ Check if returns Truthy value if (doWork()) { console.log('✅ function returns TRUTHY value'); }

The if statement checks if the return value of the function is truthy.

The if block will run if the function returns any other than the aforementioned 6 falsy values.

If you pass a value to the Boolean object and it returns true, then the if condition will be satisfied and the if block will run.

Here are some examples of passing truthy and falsy values to the Boolean object.

index.js
// 👇️ truthy values console.log(Boolean('hello')); // 👉️ true console.log(Boolean(1)); // 👉️ true console.log(Boolean([])); // 👉️ true console.log(Boolean({})); // 👉️ true // 👇️ falsy values console.log(Boolean('')); // 👉️ false console.log(Boolean(0)); // 👉️ false console.log(Boolean(undefined)); // 👉️ false console.log(Boolean(null)); // 👉️ false

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.