← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 7 of 12

JS Logical Assignment

AND Assignment

&&= only assigns the right-hand value if the variable is currently truthy — equivalent to a && (a = b), useful for updating a value only when it already exists and is meaningful.

Example: AND Assignment

javascript
let session = "active";
session &&= "updated";
console.log(session);

OR Assignment

||= only assigns if the variable is currently falsy — equivalent to a || (a = b), a compact way to set a default when a variable hasn't been given a real value yet, though it also overwrites legitimate falsy values like 0 or an empty string.

Example: OR Assignment

javascript
let name = "";
name ||= "Guest";
console.log(name);

Nullish Assignment

??= only assigns if the variable is currently null or undefined — equivalent to a ?? (a = b), the safest of the three for setting defaults without touching legitimate falsy values like 0.

Example: Nullish Assignment

javascript
let count = 0;
count ??= 10;
console.log(count); // 0, unaffected

Practical Defaults

These operators are especially handy for filling in missing object properties or config defaults in one line, instead of writing an explicit if-check before the assignment.

Example: Practical Defaults

javascript
const config = {};
config.timeout ??= 3000;
console.log(config.timeout);

Choosing the Right Operator

Pick based on what counts as missing: use ??= when only null/undefined should trigger a default, ||= when any falsy value should, and &&= when you only want to update an already-set value.

Example: Choosing the Right Operator

javascript
let a; a ??= 1; console.log(a);   // null/undefined only
let b = 0; b ||= 2; console.log(b); // any falsy
let c = "x"; c &&= "y"; console.log(c); // only if truthy

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.