Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 9, 2022 02:15 pm GMT

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

You will be aware of the Logical NOT (!) operator, which is used to negate the expression. In this article, we will see what is !! (not not) operator and its uses.

Truthy and Falsy

Before understanding the not not (!!) operator, we need to understand what is truthy and falsy in JavaScript. Truthy value is a value that is considered true in a Boolean context. That means, if we have an expression as if("John")or if(1) then this will evaluate to true. Hence, a non-empty string, non-zero number, etc are considered as truthy.

Similarly, falsy is some value that evaluates to false. Examples are 0, '' "", null, undefined etc.

Examples of truthy

The following are the expressions that will evaluate to true. Hence all the values inside the if conditions are truthy values.

if (true)if ({})if ([])if (42)if ("0")if ("false")if (new Date())if (-42)if (12n)if (3.14)if (-3.14)if (Infinity)if (-Infinity)

Examples of falsy

Following values are considered as falsy in JavaScript:

  • false
  • 0
  • -0
  • '', ""
  • null
  • undefined
  • NaN

A complete list can be found here.

The use of !! operator

Let's say we have a function called getProductDetails which returns the product details when a valid product id is passed. When an invalid product id is passed it may return an empty string or undefined. So the code for processing the product details received as a response would look like this:

const product = getProductDetails(123)if (product !== undefined || product !== "") {  // Process product details}

With the help of not not operator, we can shorten this as follows:

const product = getProductDetails(123)if (!!product) {  // Process product details}

!! is not an operator but two logical NOT (!) operators.
The first one (in the right) will convert the operand (the value under evaluation) to the negated boolean and the second ! will negate the boolean value again to get the boolean representation of the operand.

That is, !"John" will be evaluated to false and !false will be evaluated to true.

In case of a falsy value, !0 will be evaluated to true, and !true will be false.

One interesting thing to note is that !!new Boolean(false) is true because new Boolean(false) will create an object, which is truthy even though it contains a false value.


Original Link: https://dev.to/collegewap/what-is-the-not-not-operator-in-javascript-27c7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To