In Grade 3, the Professor mentioned that && and || are "lazy": they stop as soon as they know the answer. This is called short-circuiting, and it enables a few tricks you'll see in other people's code.
&& as a mini if
a && b only looks at b if a is truthy. So you can use it to run something only if a condition is true:
const isLoggedIn = true;
const isAdmin = false;
isLoggedIn && console.log("Welcome back!");
isAdmin && console.log("You have admin powers.");
It prints
Welcome back!
It works, but honestly, a plain if statement is usually clearer. You'll mostly see this trick in frameworks like React.
What && and || actually return
Here's a secret: && and || don't always return true or false. They return one of the actual values:
a || breturnsaifais truthy, otherwiseb.a && breturnsaifais falsy, otherwiseb.
console.log("pizza" || "salad");
console.log("" || "salad");
console.log("pizza" && "salad");
console.log(0 && "salad");
It prints
pizza salad salad 0
That's exactly why userName || "Guest" works as a default!
Logical assignment: ||=, &&=, ??=
These combine a logical operator with assignment, just like += combines + with assignment:
const config = { retries: 0, title: "" };
config.retries ??= 3; // only assign if null/undefined
config.title ||= "Untitled"; // assign if falsy
config.timeout ??= 5000; // missing, so it gets assigned
console.log(config);
It prints
{ retries: 0, title: 'Untitled', timeout: 5000 }x ??= y means "if x is null or undefined, set it to y." It's a tidy way to fill in missing settings without overwriting ones that already exist.