Q:

How to Convert a String to Boolean in JavaScript

0

How to Convert a String to Boolean in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Format a JavaScript Date... >>
<< How to Get the Current Date in JavaScript...