Ilya Dachkovsky Ilya Dachkovsky - 4 months ago 48
Javascript Question

No extra Boolean cast in JavaScript

In if statement's casting to a Boolean via double negation (!!) is unnecessary, because these if statements, for example, are equivalent:

if (!!foo) {
// ...
}

if (foo) {
// ...
}


But what if casting to a Boolean via !! is in return statement? Like here:

nameToSomething : function(someName){
if (someName) {
return !!this._var[someVar] ? this._var: undefined;
}
return undefined;
},


!!this._mServicesByName[someName]
in return is the same as
this._mServicesByName[someName]
here? Why?

An explanation in plain English why it is different/the same as well as examples how to circumvent this rule in JavaScript, so my linter will not "see" it will be very appreciated.

Many thanks in advance.

Answer

Ok, I've done some research myself since asking this and actually stumbled upon some very similar questions (with answers) to the double negative trick in JavaScript. Here and here I found some explanation of the need of double boolean negative trick itself. To cut the long story short it's like casting in Java. !! expression is used when you actually need to return a boolean without changing true and false. Its' a non inverted boolean or simply saying, true boolean representation.

For example this !true will be false as well as vice versa !false will be true. But by simply using !!true and !!false you can get the same true and false without changing result and still work with boolean. The same is true for !!0 being false and !!1 being true.

Now, back to my question. In the code snippets above I can't omit non inverted boolean because the functions given as examples are expecting a boolean. And false can't be change to true and vice versa. Neither it can't be replaced with a bitwise operator, because in this case it will not work. Creating a new variable above the function holding non inverted boolean an help silencing my linter, though. So it might be an answer solve the problem.

Or, alternately, changing the linter options for the "no-extra-boolean" rule in IDE will be a much better decision ) Because in JavaScript, as I learnt, they are used often and there is no way around it. It's not even a bad practice. Sometimes, when you need a true boolean representation, it's a very convenient way to write a code. And the only one.