The &&= (Logical AND Assignment) Operator
What you'll learn: How &&= assigns a value only when the left side is truthy, replacing the verbose x = x && newValue pattern.
What Is &&=?
The &&= operator is the logical AND assignment operator. It assigns a new value to a variable only if that variable currently holds a truthy value. If the variable is falsy (like null, undefined, 0, false, ""), the assignment doesn't happen at all.
Think of it like a conditional update: "If you already have something useful, replace it with this new thing. Otherwise, keep what you have (even if it's nothing)."
The Old Pattern
Before &&=, you'd write:
let user = { name: "Alice" };
user = user && { name: "Bob", verified: true };
// user is now { name: "Bob", verified: true }
let empty = null;
empty = empty && { name: "Bob" };
// empty stays null (no assignment happens)
With &&=
Now you can write it more concisely:
let user = { name: "Alice" };
user &&= { name: "Bob", verified: true };
// user is now { name: "Bob", verified: true }
let empty = null;
empty &&= { name: "Bob" };
// empty stays null
When to Use It
Use &&= when you want to upgrade or replace a value that's already present, but preserve falsy values:
let settings = { theme: "dark" };
settings &&= { theme: "light", locale: "en" };
// Replaces settings
let disabled = false;
disabled &&= true;
// disabled stays false (short-circuits)
Key Takeaway: &&= assigns a new value only if the left operand is truthy, making conditional updates cleaner and avoiding repetition of the variable name.