If I declare a JavaScript boolean variable like this:
var IsLoggedIn;
And then initialize it with either true
or 1
If you want IsLoggedIn
to be treated as a boolean you should initialize as follows:
var IsLoggedIn=true;
If you initialize it with var IsLoggedIn=1;
then it will be treated as an integer.
However at any time the variable IsLoggedIn
could refer to a different data type:
IsLoggedIn="Hello World";
This will not cause an error.
How about something like this:
var MyNamespace = {
convertToBoolean: function (value) {
//VALIDATE INPUT
if (typeof value === 'undefined' || value === null) return false;
//DETERMINE BOOLEAN VALUE FROM STRING
if (typeof value === 'string') {
switch (value.toLowerCase()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
return false;
}
}
//RETURN DEFAULT HANDLER
return Boolean(value);
}
};
Then you can use it like this:
MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false
I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!