What is the !! (not not) operator in JavaScript?

What is the !! (not not) operator in JavaScript?

In JavaScript, the !! (not not) operator is a way to force a value to become a boolean. It can be used to test the truthiness of a value and get a boolean value in return.

The ! operator is the negation operator, which inverts the truthiness of a value. For example, !true would evaluate to false, and !false would evaluate to true.

When you use the !! operator on a value, it will use the negation operator twice, so the value will be first converted to boolean, then inverted again. This will result in the original boolean value.

Here are some examples of how the !! operator works:

console.log(!!0); // Output: false
console.log(!!1); // Output: true
console.log(!!"hello"); // Output: true
console.log(!!""); // Output: false
console.log(!!null); // Output: false
console.log(!!undefined); // Output: false
console.log(!!{}); // Output: true

It is often used as a shorter way of calling Boolean() function and also it’s widely used to check truthy values in a concise way.

let a = 5;
if (!!a) {
  console.log("value is truthy");
} else {
  console.log("value is falsy");

It can also be used to ensure that a value is always truthy:

let input = "";
let value = !!input || "default value";

In this example if input variable is falsy, it assigns `default

Leave a Reply