The NOT operator, !, turns a value into true or false and flips it. In front of a missing value such as null it gives true, which makes if (!value) the usual way to check that something isn’t there.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
!value
!: the NOT operator, written right before the value.value: any value or expression.!valueistruewhen the value is falsy, such asfalse,0, an empty string,nullorundefined, andfalsefor anything else.
See Logical NOT (!) (opens in a new tab) and Falsy (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
A sign-in check with two values: signedInUser is null because nobody is signed in, and cartItems is 3. The file is sign-in.js.
Step 1: Write the Code
const signedInUser = null;
const cartItems = 3;
console.log(!signedInUser);
console.log(!cartItems);
if (!signedInUser) {
console.log("Please sign in.");
}
The first two console.log lines print what ! gives for each value. The if statement uses ! to act only when nobody is signed in.
Step 2: Run It
node sign-in.js
true
false
Please sign in.
!signedInUser is true, because null is falsy. !cartItems is false, because 3 is a value that’s there. The if block runs, so the message appears.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using ! on a number that can be 0 | !0 is true, so a real count of 0 is treated as missing | Check for the missing value itself, for example count === null |
Expecting ![] or !{} to be true for an empty list or object | Arrays and objects are truthy even when empty, so both give false | Check the length of a list: !list.length |
FAQ
What does !! do?
Two NOTs turn any value into its true-or-false form without flipping it: !!"Sam" is true.
Which values count as falsy?
false, 0, an empty string, null, undefined and NaN, plus a few rare ones that MDN lists. Everything else, including empty arrays and objects, is truthy.
Conclusion
Put ! in front of a value to get true when it’s missing or empty. if (!value) is the short way to act when something isn’t there, as long as 0 and empty text aren’t valid values for it.
Additional Resources
- Logical NOT (!) (opens in a new tab) (MDN)
- Falsy (opens in a new tab) and Truthy (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments