Open In App

Explain the ‘double negative’ Trick in JavaScript

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In programming, a “double negative” is a technique used to convert a value to its corresponding boolean value. This technique involves using two negation operators (!) to negate a value twice, resulting in a boolean representation of the original value.

The double negative technique is often used to convert truthy and falsy values to their corresponding boolean values. The following values are considered falsy in Javascript:

  • false
  • 0
  • ” ” (empty string)
  • null
  • undefined
  • NaN

Any other value is considered truthy. By applying the double negative technique, we can easily convert these values to their corresponding boolean values.

 

Example 1: In this example, we assign the string “hello” to the variable x. We then apply the double negative technique to x by negating it twice using the ! operator. The resulting value is true, which is assigned to the variable y.

Javascript




let x = "hello";
let y = !!x;
  
console.log(y); // true


Output

true

Example 2: In this example, we assign the number 42 to the variable a. We then apply the double negative technique to a by negating it twice using the ! operator. The resulting value is true, which is assigned to the variable b.

Javascript




let a = 42;
let b = !!a;
  
console.log(b); // true


Output:

true

Example 3: Here’s an example of using the double negative technique to convert a falsy value to false:

Javascript




let x = null;
let y = !!x;
  
console.log(y); // false


Output: In this example, we assign null to the variable x. We then apply the double negative technique to x by negating it twice using the ! operator. The resulting value is false, which is assigned to the variable y.

false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads