Examples
Basic Boolean Check:
JavaScript
var _ = require('lodash');
console.log(_.isBoolean(false));
console.log(_.isBoolean(0));
console.log(_.isBoolean('true'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
false
Demonstrates checking various values for Boolean type.
Validating Function Parameters:
function toggleFeature(isEnabled) {
if (!_.isBoolean(isEnabled)) {
throw new Error('Invalid parameter type');
}
// Proceed with enabling or disabling the feature
}

You can also try this code with Online Javascript Compiler
Run Code
Shows how to validate that a function parameter is a Boolean.
Conditional Logic Based on Data Types:
var data = { featureEnabled: true };
if (_.isBoolean(data.featureEnabled)) {
// Handle Boolean-specific logic
}

You can also try this code with Online Javascript Compiler
Run Code
An example of using _.isBoolean() in conditional logic based on the data type.
Filtering Booleans in an Array:
JavaScript
var mixedArray = [true, 1, 'yes', false];
var booleans = _.filter(mixedArray, _.isBoolean);
console.log(booleans);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[true, false]
Demonstrates filtering Boolean values from a mixed array.
Frequently Asked Questions
How does _.isBoolean() differ from using the typeof operator?
_.isBoolean() specifically checks for Boolean values (both true and false), while the typeof operator returns 'boolean' as a type. The Lodash method offers a more direct and explicit check.
Can _.isBoolean() detect Boolean objects created with the new Boolean() constructor?
Yes, _.isBoolean() can detect Boolean objects created with the new Boolean() constructor, as well as primitive Boolean values.
Is _.isBoolean() necessary for simple true/false checks?
For simple true/false checks, directly using conditional statements is often sufficient. _.isBoolean() is more useful for validating data types or filtering collections.
Conclusion
Lodash's _.isBoolean() method is a straightforward and reliable way to determine if a value is a Boolean. It is particularly useful in scenarios where the type of a value can significantly impact the logic or outcome of code execution.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.