4

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)

7
  • 7
    That's silly. A single application of ! will convert the value to boolean and result in the logical negation of that. The result is always either true or false. There's no reason to apply ! twice more. Commented Dec 17, 2019 at 14:08
  • 2
    Yes. (and some more letters, because the comment has a minimum length). Commented Dec 17, 2019 at 14:08
  • I know it's silly, I just needed to ask this just to be sure... some people don't see that it's the same thing Commented Dec 17, 2019 at 14:10
  • 2
    It's a particularly indecisive boolean, one that's afraid to make the hard decisions in life. Commented Dec 17, 2019 at 14:11
  • while it may be a somewhat silly question, logical not is actually one of the very few things in JS, that allow no language abuse to get even close to changing the result, after the first step. There are ways to get e.g. a !== a to work, you can do weird things if results are strings (or even better, objects), but boolean not, no chance. Commented Dec 17, 2019 at 14:12

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

I've never seen !!!foo used in actual code, but yes, they are always strictly equal.

The extra two exclamation marks just negate the boolean value twice, which always gives the same result.

Comments

1

If foo is set as boolean then !foo will be equal to !!!foo , See the example and screenshot given below

var foo = true; console.log('foo => '+foo); console.log('!foo => '+!foo); console.log('!!foo => '+!!foo); console.log('!!!foo => '+!!!foo); console.log('!!!!foo => '+!!!!foo); if(!!!foo === !foo){ console.log("Equals"); }else{ console.log("Not Equals"); } 

enter image description here

1 Comment

foo doesn't even need to be a boolean, this works for all foo.
0

While you are correct, !!!foo would equal to !foo, I've never seen JS script using !!!foo before, and I can't think of a good reason to do that. You're gonna create code smell if you write this in your own code.

In other words, don't do that.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.