Skip to main content

Why use double negation (!!) in JavaScript?

You may have seen the use of !! in JavaScript, here's why.

Double negation is used to convert a "truthy" or "falsy" value into a boolean. It's essentially used to decide if a variable contains a value.

A "truthy" value is something that translates to true when evaluated but might not actually be a boolean.

console.log("Hello" ? true : false); // true
console.log("Hello" === true); // false

The === operator is the "strict equal" operator which only returns true if the operands are equal and of the same type.

console.log(1 == "1"); // true
console.log(1 === "1"); // false

The following values in JavaScript are always "falsy", everything else is "truthy":

  • false.
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

Some examples:

console.log(!!undefined); // false
console.log(!!null); // false
console.log(!!NaN); // false
console.log(!!1); // true
console.log(!!0); // false
console.log(!!'0'); // true
console.log(!!123); // true
console.log(!!-123); // true
console.log(!!'Hello'); // true
console.log(!!''); // false

Hello, my name's Lee and I work as a full-stack web developer specialising in Microsoft ASP.NET technologies. I love using Umbraco and also MANAGED, my own interal CMS.

Contact me at lee.gunn@secretorange.co.uk

All skills

Contact

Get in touch to talk about your project or just ask me a question.

lee.gunn@secretorange.co.uk

Skype: lee_gunn