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
a && b
a: checked first. When it’s falsy, such asnull,0or empty text, the expression gives backaandbisn’t even looked at.b: what the expression gives back whenais truthy.
See Logical AND (&&) (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 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
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
node guest.js
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
| Mistake | What happens | Do this instead |
|---|---|---|
Using && with a number that can be 0 | 0 && "items" gives 0, which then shows up as 0 | Compare 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
- Logical AND (&&) (opens in a new tab) (MDN)
- 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