In JavaScript, we can use several methods to check if a variable is of Boolean type. Here are some common methods:
1. Using the typeof Operator
The typeof operator can be used to determine the type of a variable. If the variable is Boolean, typeof returns the string "boolean".
Example:
javascriptlet flag = true; if (typeof flag === 'boolean') { console.log('Variable is Boolean'); } else { console.log('Variable is not Boolean'); }
2. Using the instanceof Operator
Although instanceof is typically used to check if an object is an instance of a constructor, it is not applicable to boolean primitive types. However, for Boolean objects created with new Boolean(), you can use instanceof to verify.
Example:
javascriptlet flagObject = new Boolean(true); if (flagObject instanceof Boolean) { console.log('Variable is Boolean object'); } else { console.log('Variable is not Boolean object'); }
3. Direct Comparison
Since JavaScript's boolean type only has two values: true and false, we can directly compare the variable against these values.
Example:
javascriptlet flag = false; if (flag === true || flag === false) { console.log('Variable is Boolean'); } else { console.log('Variable is not Boolean'); }
Summary
In practical applications, using typeof is the most straightforward and commonly used method for checking boolean types. It is simple, efficient, and directly applicable to boolean primitive types. Other methods may depend on specific use cases.