Check if a Function returns True in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Aaina Sharma

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'); }

In this code snippet, we check if the return value from the function is truthy.

An easy way to think about it is - our if block will run if the function returns any other than the aforementioned 6 falsy values.

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

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 #

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