Casting a string to boolean

Lets say that we have a String with the value “false” or “true”. Lets now cast this String to a boolean value. In Java it would be


Boolean fun = new Boolean("true");

JavaScript also provides a Boolean Wrapper object, but it doesn’t really give the expected results


var notFun = Boolean("false"); // omitting new, see http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Boolean
// notFun = true

The above will only be false if false, NaN, null, 0 or an empty String is provided, everything else will return true.

So the only way to cast a String with the values “true” or “false” is to use eval…


var snowing = eval("false");

Anybody has another way to do the cast?


var stringRepresentation = "false";
var booleanRepresentation = (stringRepresentation == "true");

Thanks, yes, thats one way to do it, buy not really a cast. Its a result from a comparison. That is what I wanted to avoid.

Why?

The thing is; What you want to do is not really a type cast. You want to interpret the value of the variable – not simply change the type of it.

I am actually doing that solution now. But it felt somehow cheap compared to what Java offers. It is a pity that the Boolean wrapper object doesn’t work like it does in Java. But hey, I know, JavaScript is not Java. I wish it would be more like Java and less like Python, which it is becoming lately (JavaScript 1.7 and the upcoming 1.8).

String.prototype.reval=function(){
return eval(this);
}
This does not change the string, but returns the evaled value of the string.

If you hate eval you can define all the values-

String.prototype.reval=function(){
if(parseFloat(this)+‘’===this)return parseFloat(this);
if(this===‘false’) return false;
//etc.
}

Technically, what java does is not a typecast, but the Boolean(Stirng) constructor, that arbitrarily interprets the string “true” as boolean true. Nice? I find this kind of code rather stinky :wink:


Boolean a = new Boolean("true"); // true
Boolean b = new Boolean("true "); // FALSE

I guess that it calls parseBoolean internally, but that is another story.

Anyway, thanks for the answers everybody

:slight_smile:

No, I don’t hate eval, I use it as the last resort. Extending native objects would though be more something that I dislike.