Skip to main content
0 reactions

How to Use the NOT Operator (!) in JavaScript

A card titled The NOT Operator (!), labelled JavaScript Basics, showing that !null gives true, !3 gives false, and an if (!user) check that prints Please sign in.
The NOT Operator (!): Turn a value into true or false, and check what’s missing.

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

SyntaxJavaScript
!value
  • !: the NOT operator, written right before the value.
  • value: any value or expression. !value is true when the value is falsy, such as false, 0, an empty string, null or undefined, and false for anything else.

See Logical NOT (!) (opens in a new tab) and Falsy (opens in a new tab) on MDN.

Prerequisites

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

sign-in.jsJavaScript
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

TerminalBash
node sign-in.js
OutputPlain text
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

MistakeWhat happensDo this instead
Using ! on a number that can be 0!0 is true, so a real count of 0 is treated as missingCheck for the missing value itself, for example count === null
Expecting ![] or !{} to be true for an empty list or objectArrays and objects are truthy even when empty, so both give falseCheck 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments