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

The “not not” operator in JavaScript refers to the “double negation using the logical NOT operator (!)”. The logical NOT operator is a unary operator that returns “true” if the operand is falsey (e.g., null, undefined, false, 0, NaN, empty string ”, or document.all) and false if the operand is truthy.

When the logical NOT operator is used twice (!!), it effectively coerces a value into a boolean value, maintaining its truthiness or falseness. This is a common shorthand to convert a value into its boolean equivalent.

Keynotes

  1. !!0 returns false because 0 is a falsy value.
  2. !!1 returns true because 1 is a truthy value.
  3. !!’Hello’ returns true because a non-empty string is a truthy value.
  4. !!null returns false because null is a falsy value.

Example

const truthyValue = 'I am truthy';
const falseyValue = '';

const boolTruthyValue = !!truthyValue;
const boolFalseyValue = !!falseyValue;

console.log(`Truthy value as boolean: ${boolTruthyValue}`);
console.log(`Falsey value as boolean: ${boolFalseyValue}`);

// Another example with different values
const num1 = 0;
const num2 = 42;

const boolNum1 = !!num1;
const boolNum2 = !!num2;

console.log(`Number 1 as boolean: ${boolNum1}`);
console.log(`Number 2 as boolean: ${boolNum2}`);

Output

Truthy value as boolean: true
Falsey value as boolean: false
Number 1 as boolean: false
Number 2 as boolean: true

In this code example, we have two variables: one pair with a truthy and a falsy value (strings) and another with a truthy and a falsy value (numbers).

We used the !! operator to convert the original values to their boolean equivalents and log the results to the console.

Leave a Comment