Why use !! to coerce a variable to boolean in a conditional expression?
A few times in JS code I've seen !! used in conditional expressions like so
if(!!x) {
x.doStuff();
}
Where the idea is to test if x is defined before calling methods on it.
I understand that !!x coerces the type of x to a boolean, whilst
maintaining its truthiness or lack thereof - see this question - which
obviously makes sense for an if expression.
But, in my own code I've always just used
if(x) {
x.doStuff();
}
On the premise that if x is defined, the condition will pass, and if x is
undefined, it will not pass.
So my question is: what is the point of using !! in this scenario? What is
the difference between this and this?
I'm assuming other programmers don't just use it because it looks cool, so
either this or one of my other assumptions is wrong :-)
No comments:
Post a Comment