js typecast to boolean code example

Example 1: string to boolean js

// Everyone does one extra check. Here is a better answer

let toBool = string => string === 'true'; // ? true : false;
// Not everyone gets ES6 so here for the beginners
function toBool(string){
	return string === 'true';
}

Example 2: js string to boolean

// Do
var isTrueSet = (myValue == 'true');
// Or
var isTrueSet = (myValue === 'true');

Example 3: convert string true to boolean true javascript

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}

Tags:

Java Example