Reputation: 128
I have the following code to try the difference between using Direct assigning and assigning with !!
var a = true,
b = true;
a = b;
alert(a);
a = !!b;
alert(a);
does it have difference in using or result i can't compare each of their result
Upvotes: 0
Views: 75
Reputation: 562
It's not different. The result will be the same as that of a direct comparison.
The use case for using !! is: Many times it happens that you want to check a non-boolean against a boolean value or check whether a value is true or false inside an if condition. This is exactly when you would want to use !!.
What !! does is, it first negates the value of the variable and then again negates the value obtained in the previous negation.
Say for e.g. if you use it like this:
var str = "";
console.log(!!str);
This would give you the boolean value of false.
You should use !! When you are required to do a strict check for truthness of a condition. Something like this:
if (true === !!str) {
console.log('true');
} else {
console.log('false');
}
Upvotes: 1
Reputation: 6561
!!x
is commonly used as a shortcut for Boolean(x)
. I just ran a little test and the double negation has exactly zero performance cost. Even when the assigned value is not a constant and even when it is not a Boolean to begin with. Boolean conversion is so simple that it's basically free.
Upvotes: 1
Reputation: 59232
There is no difference, per se. But a = !!b
is slightly less efficient, I believe.
Since, first it's converted to false
and again converted to true
.
Don't know if this is a case of micro-optimization, but a = b
would be the straight-forward way and more readable.
Upvotes: 1