Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is !!!foo the same as !foo? [duplicate]

Tags:

javascript

Knowing that !!foo gives you the Boolean value of foo, I have seen some programmers say that it's better to use !!!foo instead of !foo because you are changing it to its Boolean value first and then negating the value.

So my question is,

Is !!!foo always equals !foo? (!!!foo === !foo)

like image 718
Vencovsky Avatar asked Dec 31 '22 10:12

Vencovsky


1 Answers

Yup. Just for clarity:

!!x === x is not generally true, but it is true if x is already a boolean: "not (not true)" is true, and "not (not false)" is false.

!foo is always a boolean; if foo is truthy, it's false, otherwise it's true.

So if you substitute !foo in for x you get that !!(!foo) === (!foo) is always true. Removing the parentheses doesn't change the meaning, so !!!foo === !foo is always true.

Which means there's no good reason to write !!!foo in actual code. Just use !foo instead.

like image 54
Mark Reed Avatar answered Jan 02 '23 22:01

Mark Reed