HomeTutorsContact

Double exclamation mark !! (not not) operator in JavaScript?

By Gulshan Saini
Published in JavaScript
December 09, 2021
1 min read

If you have ever noticed a double exclamation mark (!!) before the variable in someone’s JavaScript code you may be curious what it’s for and what it does.

!! is not an operator. It’s just the ! operator twice. It converts a non-boolean to an inverted boolean (for instance, !9 would be false since 9 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!9 would be true)

Let’s see the following examples

!!false === false
!!true === true

!!0 === false
!!1 === true

!!"" === false // empty string is falsy
!!undefined === false // undefined primitive is falsy
!!null === false // null is falsy

!!{} === true  // an (empty) object is truthy
!![] === true  // an (empty) array is truthy

!! operator results in a double negation.

However as a good practice and to make your code more readable you should use the Boolean constructor. If we modify the above examples and replace !! with Boolean() constructor, we get the same results

Boolean(false) === false // true
Boolean(true) === true // true

Boolean(0) === false // true
Boolean(1) === true // true

Boolean("") === false // empty string is falsy
Boolean(undefined) === false // undefined primitive is falsy
Boolean(null) === false // null is falsy

Boolean({}) === true  // an (empty) object is truthy
Boolean([]) === true  // an (empty) array is truthy

Tags

#javascript
Previous Article
Exclamation mark before a variable in JavaScript?

Related Posts

JavaScript
JavaScript get tomorrow's date
December 13, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
Linux
JavaScript
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2022, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media