Since JavaScript is a dynamically typed language, its variables can contain data of any type.
Therefore, we need a way to check for the data type of a variable.
In this article, we’ll look at ways to check if the data type of a JavaScript variable is a boolean.
The typeof Operator
One way to check if a variable is a boolean variable is using the typeof
operator.
To do this, we write:
if (typeof variable === "boolean") {
// ...
}
We check if the data of the variable
variable is a boolean with the expression if the if
statement.
It’ll return true
if variable
is a boolean.
The === Operator
Another way to check is a variable is a boolean is to check if it equals to true
or false
with the ===
operator.
For instance, we can write:
const isBoolean = (val) => {
return val === false || val === true;
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))
We create the isBoolean
that checks whether val
is false
or true
.
Since we use the ===
operator, either expression in the OR expression will return true
only if val
is exactly equal to the value being compared.
Therefore, the first console log should log true
.
And the 2nd one should log false
.
Check the String Representation of the Variable with toString
In addition to checking if the value is exactly equal to true
or false
, we can also compare the string value of it to see if it’s a boolean.
For instance, we can write:
const isBoolean = (val) => {
return val === true || val === false || toString.call(val) === '[object Boolean]';
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))
We call toString.call
with our val
parameter to see if it returns ‘[object Boolean]’
.
If it does, then it gives us more confidence that val
is a boolean.
Using the valueOf Method
In case that we have boolean variables that are boxed with the Boolean
constructor, we can also call the valueOf
method to return the primitive version of the boolean variable.
For instance, we can write:
const isBoolean = (val) => {
return typeof val === 'boolean' ||
(
typeof val === 'object' &&
val !== null &&
typeof val.valueOf() === 'boolean'
);
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))
to add:
(
typeof val === 'object' &&
val !== null &&
typeof val.valueOf() === 'boolean'
)
to check if val
is an object that isn’t null
but the when we call valueOf
it, we get 'boolean'
returned.
This expression would be true
if we invoke the Boolean
constructor by writing expressions like:
new Boolean(true)
to create a boxed boolean object.
The console logs should be the same as the previous examples.
Conclusion
There’re many ways we can use to check if a JavaScript variable is a boolean variable.