Lajos Arpad Lajos Arpad - 3 months ago 10
Javascript Question

Is there any difference between variable usage and double exclamation in an if?

Let's suppose I have a variable

condition
. If I want to store it into a variable as a strict
boolean
value, then I do something like this:

var logicalCondition = !!condition;


The first exclamation negates
condition
and converts the value into a
boolean
. The second exclamation negates the negated strict boolean value back. The result is
true
if
condition
was truey and is
false
if
condition
is falsy.
If
conditions are known to convert truey to
true
and falsy to
false
. So, if we take a look at the following two chunks

//first
if (condition) {
//do something
}

//second
if (!!condition) {
//do something
}


the first difference we can observe is that in the second case we convert the value into strict
boolean
value before we hand it to the
if
. Is there a second difference, or is this conversion unnecessary?

Answer

Is there a second difference...?

No, there isn't, at the JavaScript engine's level. As you've said, the test done by if (and anywhere else a boolean is required) will do the same thing that !! is doing (in effect). So your first difference (the extra work) is the only difference.

Comments