What does the ! operator do in JavaScript?

What does the !! operator do in JavaScript? I came across this code:

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

It seems to be using !! as an operator, which I don’t recognize. Can you explain what the javascript double bang does?

Hey!

When using the double exclamation mark (!!), you’re essentially converting a value to its Boolean representation. Here’s how it works:

  1. The first ! (logical NOT) flips the truthiness of the value:

    • If the value is falsy (like 0, null, undefined, etc.), it becomes true.
    • If the value is truthy (like a non-empty string or number), it becomes false.
  2. The second ! then flips the value back to its original truthiness, but now as an explicit Boolean (true or false).

This technique is handy for explicitly converting any value to a Boolean type.

Examples:

console.log(!!0);         // false (0 is falsy)
console.log(!!1);         // true (1 is truthy)
console.log(!!"hello");   // true (non-empty string is truthy)
console.log(!!null);      // false (null is falsy)

Hope this helps clarify how !! works in JavaScript!

Readability and Intent: While you can achieve the same effect using Boolean(vertical), the !! operator is often favored for its brevity. However, some developers argue that Boolean() might be clearer in terms of intent, especially for those unfamiliar with the double bang convention.