JavaScript

Why use double negation in JavaScript

March 16, 2022

Why use double negation in JavaScript

In this article we will learn why to use double negation in JavaScript and the ways to apply this form of Boolean evaluation in your code

why to use double negation in JavaScript

Hey you programmer, how are you? Let’s learn more about JavaScript!

Let’s first explain the NOT or ! in JavaScript.

It basically converts the operator being used to its opposite

So !true becomes false and !false becomes true

And consequently the second ! returns the actual value the value has, thus the fastest way to check if a value is true or false in JavaScript

This is the great insight of the double negative!

In this way we will simplify the conditional evaluation processes

Practical Examples

For example, let’s evaluate whether a variable contains any value:

let a = "Has some value";

let b;

if(!!a) {
 console.log("a variable has a value");
}
if(!!b) {
 console.log("a variable has not a value");
}

Here in this example only the variable “a” has any value, so the double negative validation kicks in, just submitting the first check to true

Since the void of a variable returns by default the value false

Here are some more values that return false in JavaScript:

  • False
  • NaN
  • Undefined
  • Null
  • “” (empty string)
  • 0

All these double negative (!!) values will return false to you when applied to some conditional

The others will return true

In addition to this advantage, the value is automatically converted to a boolean, that is, we have a typecast to boolean

Conclusion

In this article we learned how to use double negation in JavaScript

We can implement this operator when we want quick validation of a sentence

And the check returns a boolean as an answer, i.e. true or false

Click here to see more articles about JavaScript!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x