The NOT operator

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

The NOT operator

The NOT operator (!) flips truthy and falsey values around. Truthy values becomes false while falsey values become true.

console.log(!22) // false
console.log(!false) // true

The NOT operator can be used to eliminate else statements, like this:

const str = ''

if (!str) {
  // Only do something if string is empty (NOT truthy)
}

Double negation

You may notice that developers sometimes use two NOT operators together:

!!someVariable

!! here is called a double negation. It does the following:

  1. converts a truthy value to true
  2. converts a falsey value to false

It works this way: if the value is truthy, convert it to false with the first ! NOT operator; then, convert false to true again with the second ! NOT operator (and vice versa).

Double negation is used to explicitly cast a truthy or falsey value into a boolean (true or false). You’ll almost never need it.

Exercise

What’s the result of each of these expressions?

  1. !2550284
  2. !true
  3. !NaN
  4. !{}
  5. !!'Pandas are adorable!'
  6. !!''

Answers

What’s the result of each of these expressions?

  1. !2550284. false
  2. !true. false
  3. !NaN. true
  4. !{}. false
  5. !!'Pandas are adorable!'. true
  6. !!''. false