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 .

#programming #javascript #technology

How to Check If The Type Of A JavaScript Variable Is Boolean?
1.50 GEEK