The ! (NOT) Operator
You'll learn how to flip any value to its opposite boolean using the NOT operator.
What is the ! Operator?
The ! operator (pronounced "bang" or "NOT") takes any value and flips it to the opposite boolean. If something is truthy, ! makes it false. If something is falsy, ! makes it true.
Think of it like a light switch — whatever state the light is in, flipping the switch gives you the opposite.
How It Works
Place ! directly in front of any value or expression:
!true // false
!false // true
The magic happens when you use ! with non-boolean values. JavaScript first converts the value to its boolean equivalent (truthy or falsy), then flips it:
!1 // false (1 is truthy, flip to false)
!0 // true (0 is falsy, flip to true)
!"hello" // false (non-empty string is truthy)
!"" // true (empty string is falsy)
!null // true (null is falsy)
!undefined // true (undefined is falsy)
Practical Uses
The ! operator is commonly used to:
- Invert boolean conditions:
if (!isLoggedIn) - Check for "emptiness":
if (!username) - Convert and flip in one step:
!value
You can also use !! (double negation) to convert any value to its actual boolean without flipping, but you've already seen that technique.
Key Takeaway: The ! operator negates any value, turning truthy values into false and falsy values into true — it's your tool for logical inversion.