javascript / intermediate
Snippet
Logical Assignment Operators
Logical assignment operators combine logical operations (??, ||, &&) with assignment (=). They are useful for setting default values or updating state conditionally.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let user = {id: 101,preferences: { theme: 'dark' },accessCount: 0};// Nullish coalescing assignment (assigns if null or undefined)user.preferences.lang ??= 'en';// Logical OR assignment (assigns if falsy)user.accessCount ||= 1;// Logical AND assignment (assigns if truthy)user.id &&= 'ID_' + user.id;console.log(user);
Breakdown
1
user.preferences.lang ??= 'en';
Assigns 'en' only if lang is null or undefined (not for empty string or 0).
2
user.accessCount ||= 1;
Assigns 1 because the current value (0) is falsy.