Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

JavaScript `&&=`: Logical AND Assignment

1 min read .
JavaScript `&&=`: Logical AND Assignment

The logical AND assignment operator, &&=, assigns a new value to its left-hand operand only when the current value is truthy.

Basic Syntax

variable &&= newValue;

Conceptually, this is similar to:

if (variable) {
  variable = newValue;
}

Example

let status = 'ready';
status &&= 'updated';

console.log(status); // 'updated'

If the current value is falsy, it is preserved:

let enabled = false;
enabled &&= 'yes';

console.log(enabled); // false

Object Properties

const settings = {
  theme: 'dark',
  notifications: false,
};

settings.theme &&= 'light';
settings.notifications &&= true;

console.log(settings);
// { theme: 'light', notifications: false }

Short-Circuit Behavior Matters

The right-hand expression is evaluated only when the left side is truthy:

let cache = null;
cache &&= expensiveOperation(); // expensiveOperation() is not called

That is why &&= is more than simple shorthand for unconditional assignment.

Do Not Confuse &&= with &=

&&= is logical AND assignment. &= is bitwise AND assignment:

let value = 6; // 110
value &= 3;    // 011
console.log(value); // 2

Conclusion

Use &&= when the left-hand value itself should be replaced only if it is currently truthy. It is concise for conditional property updates, but an ordinary if statement can be clearer when the condition or assignment is more complex.

Related Posts

chevron-up