3

I know, I know, sounds silly, but I am having this one variable passed around and around and I think somewhere in the midst of it all its losing itself as a Boolean Value, that being the case I need to take said string when it comes to one portion of my script and make sure its read as a Boolean. So with that, I am wondering if theres something like the parseInt function but for booleans cause I know when my int's manage to get run through the mill and turn into a string cause of, I sometimes need to invoke a means of making it recognize as integer again.

0

3 Answers 3

3
String.prototype.parseBoolean = function ()
{
  return ("true" == this.toLowerCase()) ? true : false
}
Sign up to request clarification or add additional context in comments.

1 Comment

adding to native objects prototype is generally frowned upon these days stackoverflow.com/questions/6877005/… - also can be simplified by getting rid of the ternary statement and just returning the comparison.
2

no there is no function, there is this shortcut:

var bool = !!something;

or, you can make a new boolean like this:

var bool = Boolean(something)

it works by coercing the value to a boolean. It will use the truthy/falsy value for the variable.

while i am on this topic, there is also:

var floor = ~~3.1415; //floor = 3

1 Comment

Warning if anyone stumbles on this: !!"false" === true. And Boolean("false") === true.
0
function stringToBoolean(string){
    if (typeof string === "undefined") {
        console.log("stringToBoolean Undefined Error");
        return false;
    }
    if (typeof string === "boolean") return string;
    switch(string.toLowerCase()) {
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return false;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.