How to check if type is Boolean using JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

Check if type is Boolean using JavaScript #

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.

index.js
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:

index.js
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 executed.

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.

index.js
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.

Our conditions check if the value is equal to true, or the value is equal tofalse. Since booleans only have true or false values, if either check passes, we have a boolean.

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