Skip to main content
0 reactions

How to Use the && Operator in JavaScript

A card titled The && Operator, labelled JavaScript Basics, showing member && member.name giving Sam and guest && guest.name giving null.
The && Operator: Use a value only when the one before it is there.

The && operator, logical AND, is true when both sides are. It also works on any values: a && b gives back b when a is truthy, and a itself when a is falsy. That makes user && user.name a way to read a property only when the object is there.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
a && b
  • a: checked first. When it’s falsy, such as null, 0 or empty text, the expression gives back a and b isn’t even looked at.
  • b: what the expression gives back when a is truthy.

See Logical AND (&&) (opens in a new tab) on MDN.

Prerequisites

The Example

A member with a name, and a guest who is null. Each line reads the name only if the person is there. The file is guest.js.

Step 1: Write the Code

guest.jsJavaScript
const member = { name: "Sam" };
const guest = null;

console.log(member && member.name);
console.log(guest && guest.name);

Without &&, guest.name would stop the program, because null has no properties.

Step 2: Run It

TerminalBash
node guest.js
OutputPlain text
Sam
null

member is there, so you get member.name. guest is null, so you get null back and guest.name is never read.

Common Mistakes

MistakeWhat happensDo this instead
Using && with a number that can be 00 && "items" gives 0, which then shows up as 0Compare first: count > 0 && "items"

FAQ

Does a && b always give true or false?

No. It gives back one of its two values. Only when both are true or false is the result a boolean.

Conclusion

a && b gives b only when a is there, and a otherwise. Watch out for 0, which is falsy but still a value.

Additional Resources

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

0 comments