Example 1 — Guard with &&
Run code only if left is truthy.
JavaScript
const user = { name: "Ada" };
user && console.log(user.name); How It Works
- user is truthy, so right side runs.
&& and || short-circuit: they stop when the result is known. ! negates truthiness. They return an operand value, not always a boolean.
console.log(true && "ok");
console.log(false || "fallback");
console.log(!""); Run code only if left is truthy.
const user = { name: "Ada" };
user && console.log(user.name); Careful: 0 becomes fallback.
console.log(0 || 5); Force a boolean.
console.log(!!"hi"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful