When building a jQuery plugin that is supposed to be passed a Boolean value, what’s the most fool-proof way of converting the input to a Boolean in a user-friendly way?
To be more precise: I am afraid of the case that people might pass a String of 'false' (instead of a plain false) and therefore a simple conversion of !!option or Boolean(option) will return the “wrong” value (!!'false' is true).
At the moment I am checking my var option like this:
if (typeof(option) != 'boolean'){
if (option === 'false'){
option = false; //fake false
} else {
option = !!option; //everything else is converted as truthy / falsy in a standard manner
}
}
but I was wondering if there is a more elegant and concise way to do so, or is this just the way that JavaScript handles this?
The most fool proof way, if you are afraid of such input, is to do just
Look at the solution you have now, you didn’t take into account
0or1. Or what aboutnooryes?Strings and Integers aren’t meant to be used as Booleans; so, there is no need to parse them.
Take a look at high quality / usage JS frameworks, they don’t do this. Why should you?