-1

I'm trying to understand what exactly the double exclamation mark does. Yes, I saw this question, with lots of answers. So I know in principle what it does, but I don't know why one would ever need to use it.

From what I understand, it converts the value to a boolean. So let's say I have the following code:

var myBool = !!(index === 0 || index > len);

Can't I just leave out the !! and I will get the same result:

var myBool = (index === 0 || index > len);

What do I gain by adding !!? Is't it already a boolean vaule?

Community
  • 1
  • 1
Horay
  • 1,318
  • 1
  • 17
  • 33

1 Answers1

6

The purpose of !! is to canonicalize any type of truthy or falsey value to the corresponding boolean value.

If the value is already known to be a boolean, such as the result of a comparison operator, there's no point in it and it's redundant. So it's useless in the example you gave.

Barmar
  • 669,327
  • 51
  • 454
  • 560