Horay Horay - 7 months ago 54
Javascript Question

Understanding the double exclamation point

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?


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.