The NOT operator (!) flips truthy and falsey values around. Truthy values becomes false while falsey values become true.
console.log(!22) // falseconsole.log(!false) // trueThe 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:
- converts a truthy value to
true - 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?
!2550284!true!NaN!{}!!'Pandas are adorable!'!!''
What’s the result of each of these expressions?
!2550284— false!true— false!NaN— true!{}— false!!'Pandas are adorable!'— true!!''— false
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson