Borislav Hadzhiev
Sun Nov 07 2021·2 min read
Photo by Aaina Sharma
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.
function doWork() { // logic ... return true; } // 👇️ Check if returns explicitly `true` if (doWork() === true) { console.log('✅ function returns true'); }
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).
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.
// 👇️ 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