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.

chris
  • 36,115
  • 52
  • 143
  • 252

3 Answers3

3
String.prototype.parseBoolean = function ()
{
  return ("true" == this.toLowerCase()) ? true : false
}
odiszapc
  • 4,089
  • 2
  • 27
  • 42
  • 2
    adding to native objects prototype is generally frowned upon these days http://stackoverflow.com/questions/6877005/extending-object-prototype-javascript - also can be simplified by getting rid of the ternary statement and just returning the comparison. – mkoryak Jun 15 '12 at 02:29
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
mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • Warning if anyone stumbles on this: !!"false" === true. And Boolean("false") === true. – tru7 Feb 22 '21 at 19:31
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;
    }
}
Andrew
  • 3,733
  • 1
  • 35
  • 36