Learnitweb

Double not (!!) in JavaScript

Double not (!!) is used to convert any value to its corresponding boolean primitive. That is, a truthy value to primitive true and a falsy value to primitive false. The conversion is based on the truthy and falsy value of the operand used with double not (!!).

How it works?

  1. In first step, first not (!) returns false if its operand can be converted to true; otherwise, returns true. So in the first step, a truthy value is converted to false and a falsy value is converted to true.
  2. The second not then again does the same; returns false if its operand can be converted to true; otherwise, returns true.

Examples

  1. Number 5 is a truthy value, so !!5 is true.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(!!5); // 5
console.log(!!5); // 5
console.log(!!5); // 5

2. empty string is falsy, so !!'' is false.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(!!''); //false
console.log(!!''); //false
console.log(!!''); //false

3. Any object is truthy, so !!{} is true.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(!!{});
console.log(!!{});
console.log(!!{});

The same can be achieved using Boolean function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(Boolean(5)); //true
console.log(Boolean("")); //false
console.log(Boolean({})); // true
console.log(Boolean(5)); //true console.log(Boolean("")); //false console.log(Boolean({})); // true
console.log(Boolean(5)); //true
console.log(Boolean("")); //false
console.log(Boolean({})); // true