How to Convert a String to Boolean in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the ===
Operator
You can simply use the strict equality operator (===) if you wants to convert a string representing a boolean value, such as, 'true' or 'false' into an intrinsic Boolean type in JavaScript.
Let's take a look at the following example to understand how it basically works:
Example
Try this code »// Defining a custom function
function stringToBoolean(value){
return (String(value) === '1' || String(value).toLowerCase() === 'true');
}
// Performing some tests
console.log(stringToBoolean(true)); // Prints: true
console.log(stringToBoolean("true")); // Prints: true
console.log(stringToBoolean("True")); // Prints: true
console.log(stringToBoolean("TRUE")); // Prints: true
console.log(stringToBoolean(false)); // Prints: false
console.log(stringToBoolean("false")); // Prints: false
console.log(stringToBoolean("False")); // Prints: false
console.log(stringToBoolean(undefined)); // Prints: false
console.log(stringToBoolean(null)); // Prints: false
console.log(stringToBoolean(1)); // Prints: true
console.log(stringToBoolean(0)); // Prints: false
Related FAQ
Here are some more FAQ related to this topic: