Arnaud Denoyelle Arnaud Denoyelle - 5 months ago 8
Javascript Question

Why "if(!!variable)" instead of "if(variable)"?

In someone else's code I found this way to test the existence of a variable :

if(!!variable) {
//Do something
} else {
//Something else
}


Is there a reason to test with
if(!!variable)
instead of
if(variable)
? Is it a good practice?

Answer

Is there a reason to test with if(!!variable) instead of if(variable)?

No.

Using if() will coerce the condition to a boolean anyway, there's no need to manually do it. Using this sort of syntax makes sense when you want to guarantee you've got a boolean elsewhere, for example if you wanted to log the truthiness of the expression:

console.log(!!variable)

This will ensure that you get either true or false logged, rather than the original value of the variable. But inside an if? It makes no difference.

Comments