Normalizing a boolean in JavaScript
I’m assuming that you’ve already seen code which looks like this:
function doSomething(isTrue) {
if (!!isTrue ) {
//some code here
}
}
And I’m sure you’re wondering what’s going on there. This is sometimes called boolean normalization and its main advantage is that you end up getting a true boolean value instead of relying on the use of truthly and falsy values in JavaScript. Lets walk this step by step, shall we? When you have something like this:
var aux = !isTrue;
you’re using the ! operator to “negate” the current expression. As you know by now, JavaScript has several falsy values (ie, values which represent false –ex.: 0 is always converted into false). When we apply the ! operator for the first time, we end up converting the isTrue variable to a boolean and negating it. The second ! ends up negating that intermediate expression and we end up with the correct boolean value for the initial expression. Many consider this a bad practice and prefer to use other approaches. For instance, you could get the same result by using the Boolean function:
function doSomething(isTrue) {
if (Boolean(isTrue)) {
alert("YES!");
}
}
Btw, don’t fall to the temptation of using a Boolean object, ie, don’t call new Boolean(isTrue) for converting the value to a boolean. If you do that, you’ll end up creating a new *object* which wraps a boolean value. Since we’re talking about a non null value, you’ll always end with a true expression and this is not what we want here!
Even though the code is somewhat cryptic and consider by many as a “poor man’s boolean conversion operator”, it’s code that most savvy JS programmers use because it’s compact and simple. I’ve been using this technique whenever I need to ensure the use of a proper boolean value. And that’s all for today. Stay tuned for more on JavaScript.