Open In App

Explain the ‘double negative’ Trick in JavaScript

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:



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.




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.




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:




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

Article Tags :