Borislav Hadzhiev
Sat Oct 30 2021·2 min read
Photo by Manuel Meurisse
Use the typeof
operator to check if a value is of boolean type, e.g.
if (typeof variable === 'boolean')
. The typeof
operator returns a string
that indicates the type of a value. If the value is a boolean, the string
"boolean"
is returned.
const bool = true; if (typeof bool === 'boolean') { console.log('✅ type is boolean'); } else { console.log('⛔️ type is NOT boolean'); }
We used the typeof operator to get the type of a value.
The operator returns a string that indicates the value's type. Here are some examples:
console.log(typeof true); // 👉️ "boolean" console.log(typeof false); // 👉️ "boolean" console.log(typeof function () {}); // 👉️ "function" console.log(typeof null); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof {}); // 👉️ "object" console.log(typeof ''); // 👉️ "string" console.log(typeof 0); // 👉️ "number"
When used with a value of true
or false
, the typeof
operator returns the
string "boolean"
and that' exactly what we check for in our if
statement.
If the condition is satisfied, the if
block gets ran.
An alternative approach is to use the logical OR (||) operator.
To check if a value is of boolean type, check if the value is equal to false
or equal to true
, e.g. if (variable === true || variable === false)
. Boolean
values can on be true
and false
, so if either condition is met, the value
has a type of boolean.
const bool = true; if (bool === true || bool === false) { console.log('✅ type is boolean'); } else { console.log('⛔️ type is NOT boolean'); }
This example achieves the same goal as the previous.
This time, we used the logical or (||) operator to chain 2 conditions. If either
condition returns a truthy value, the if
block is ran.
true
, or the value is equal tofalse
. Since booleans only have true
or false
values, if either check passes, we have a boolean.