The logical AND assignment operator &&=
arrived alongside ??= in ECMAScript 2021. It combines logical AND &&
with assignment =
, offering a shorthand way to conditionally update values.
The &&=
operator is a logical assignment operator that updates values based on truthiness. It only assigns the new value if the existing value is truthy. Here’s how it works under the hood:
The behavior of &&=
becomes clear when we examine different initial values.
Starting with true
(truthy), the value changes to ‘granted’; but with false
, an empty string, or 0 (all falsy values), the original value stays unchanged.
This demonstrates how &&=
only performs assignment when the existing value is truthy, making it ideal for conditional updates where you want to preserve falsy states.
The &&=
operator excels at handling conditional updates where you want to respect falsy values. Here’s a common use case with user permissions:
The &&=
operator is also useful for managing application states and validation:
Or for an API response pattern:
Keep in mind that the &&=
operator is about conditional updates based on truthiness. If you need to handle null
or undefined
specifically, consider using the ??=
operator instead.