How to check if type is Boolean using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 the 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's exactly what we check for in our if statement.

index.js
const bool = true; if (typeof bool === 'boolean') { console.log('✅ type is boolean'); }

If the condition is satisfied, the if block runs.

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

We used the logical or (||) operator to chain 2 conditions. If either condition returns a truthy value, the if block runs.

Our conditions check if the value is equal to true or equal to false.

Since booleans can only ever be true or false, if either check passes, the value is a boolean.

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.