!!x
coerces the type of variable x
to a boolean, whilst maintaining its truthiness or lack thereof - see this question - I have a question about the use of this in conditional expressions.
A few times in JS code I've seen !!
used to coerce a variable to boolean type in an if
condition like so
if(!!x) {
x.doStuff();
}
Where the idea is to test if x
is defined before calling methods on it.
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 coercing x
to a boolean using !!
in this scenario? What does this code do that this code doesn't?