This post will describe the methods to check if the type of variable is boolean or not using JavaScript.
How to Check/verify if the Type is Boolean Using JavaScript?
To determine if the variable type is boolean or not, use the following predefined methods:
- typeof operator
- strict equality operator (===)
- call() method
Let’s examine the working of the above methods.
Method 1: Check if the Type is Boolean Using typeof Operator
Utilize the “typeof” operator to determine if the variable type is boolean or not. More specifically, this operator can compare the variable type to the specified type with the help of the strict equality operator.
Syntax
Follow the given syntax to use the typeof operator:
Example
Create a variable “a” and assign value “true”:
Call the “typeof” operator in the “console.log()” method with a strict equality operator to check whether the value of the variable “a” is boolean or not:
The output displayed “true” which indicates the variable is boolean:
Method 2: Check if the Type is Boolean Using Strict Equality Operator (===)
To determine if the type of variable is boolean, use the “===” operator. The strict equality operator compares variables based on both their type and their value, and it returns a boolean value.
Syntax
For strict equality operator, use the below syntax:
Example
Check the variable with a strict equality operator with the boolean value “true”:
The output displays “true” as both operands of the strict equality operator are the same in terms of type and value:
Method 3: Check if the Type is Boolean Using tostring.call() Method
To determine whether a variable is a boolean or not, utilize the “tostring.call()” method. It works or behaves similarly to the typeof operator.
Syntax
The toString.call() method can be used with the following syntax:
Here, pass the variable “x” as an argument to the method and match it with “[object data_type]”.
Example
Call the toString.call() method by passing the variable and then matching it with the ‘[object Boolean]’. If it gets matched, the method will return “true” else, “false”:
The corresponding output will be as follows
All the necessary information is compiled related to verifying the type of the variable, is it boolean or not?
Conclusion
To check if the type is boolean, use the “typeof” operator, “strict equality” operator (===), or “tostring.call()” method. All these approaches give effective results; however, the “typeof” operator is the most commonly used method in JavaScript to determine the variable type. This post described the methods to check if the type of variable is boolean or not using JavaScript.