Harnessing the Null Coalescing Assignment Operator (`??=`)
Aug 01, 2025 am 07:43 AM??= assignment operation only takes effect when null or undefined on the left, 1. Used to set the default configuration value, such as user.age ??= 18; 2. Implement lazy initialization of variables, such as cache ??= initializeHeavyResource(); 3. Retain valid values when merging optional object properties, such as userData.email ??= getDefaultEmail(); this operator will not overwrite falsy values such as 0, '' or false, which is safer than ||=, and is suitable for modern environments, ultimately making the code more concise, safe and predictable.
The null coalescing assignment operator ( ??=
) is a concise and powerful feature introduced in modern JavaScript (ES2021) that helps streamline conditional assignments based on null
or undefined
checks. It's particularly useful when you want to assign a default value to a variable only if it's currently null
or undefined
.

What ??=
Actually Does
The ??=
operator works like this:
a ??= b;
This means:
"If a
is null
or undefined
, assign b
to a
. Otherwise, leave a
unchanged."

It's equivalent to writing:
if (a == null) { a = b; }
But much more compact and readable.

? Important:
??=
only triggers assignment if the left-hand side isnull
orundefined
— not other false values like0
,''
, orfalse
.
When to Use ??=
1. Setting Default Configuration Values
When working with user-provided options, you often want to fill in defaults only when certain properties are missing.
function createUser(settings) { const user = {}; user.name = settings.name ?? 'Anonymous'; user.age ??= settings.age ?? 18; user.isActive ??= settings.isActive ?? true; return user; }
Or more cleanly:
function createUser(settings) { const user = { name: 'Anonymous', age: 18, isActive: true }; user.name ??= settings.name; user.age ??= settings.age; user.isActive ??= settings.isActive; return user; }
This avoids overwriting with undefined
while preserving intentional falsy values.
2. Lazy Initialization of Variables
You can use ??=
to initialize expensive or conditional values only when needed.
let cache; cache ??= initializeHeavyResource(); // runs only once
Even if cache
is reassigned to null
later, this pattern allows reinitialization — unlike ||=
which would fail on falsy results.
?? Compare with
||=
:
||=
triggers on any false value (0
,''
,false
, etc.), which can lead to bugs.
??=
is safe because it only cares aboutnull
andundefined
.
3. Working with Optional Object Properties
When merging partial data, ??=
helps preserve existing state.
const userData = { id: 123, name: 'Alice' }; userData.email ??= getDefaultEmail(userData.name); userData.role ??= fetchDefaultRole(); // async or computed
This avoids accidentally clearing valid but empty strings or false
values.
Practical Example: Config Manager
class Config { constructor() { this.apiKey = null; this.timeout = 0; this.retries = false; } applyDefaults() { this.apiKey ??= process.env.API_KEY; this.timeout ??= 5000; this.retries ??= 3; } }
Here:
-
timeout
is0
→ kept as0
(not replaced) -
retries
isfalse
→ keep asfalse
- Only truly missing values (
null
) get defaults
This behavior makes ??=
ideal for configuration systems.
Limitations and Gotchas
- Not available in older environments — requires ES2021 (Node.js 16 , modern browsers). Use Babel or checks in legacy code.
- Cannot be used directly on object destructuring like default params, but similar logic applications:
// Destructuring with defaults still uses `=`, not `??=` const { name = 'Default' } = obj; // But you can do: let { apiKey } = obj; apiKey ??= 'fallback-key';
- Short-circuiting matters : The right-hand side is evaluated only if the left is
null
/undefined
.
let x = 1; x ??= console.log('This won't run'); // no output
Summary
Use ??=
when:
- You want to assign defaults only for
null
/undefined
- You need to preserve false values like
0
,''
, orfalse
- You're doing lazy initialization or merging partial data
Avoid ||=
in these cases — it's too broad.
Basically:
??=
= "only assign if really missing"
||=
= "assign if false" — often too aggressive
With ??=
, your code becomes cleaner, safer, and more predictable when handling optional values.
The above is the detailed content of Harnessing the Null Coalescing Assignment Operator (`??=`). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using === instead of == is the key to avoid PHP type conversion errors, because == will cause unexpected results, and === compare values and types at the same time to ensure accurate judgment; for example, 0=="false" is true but 0==="false" is false, so when dealing with return values that may be 0, empty strings or false, === should be used to prevent logical errors.

Avoidnestedternariesastheyreducereadability;useif-elsechainsinstead.2.Don’tuseternariesforsideeffectslikefunctioncalls;useif-elseforcontrolflow.3.Skipternarieswithcomplexexpressionsinvolvinglongstringsorlogic;breakthemintovariablesorfunctions.4.Avoid

The alternative control structure of PHP uses colons and keywords such as endif and endfor instead of curly braces, which can improve the readability of mixed HTML. 1. If-elseif-else starts with a colon and ends with an endif, making the condition block clearer; 2. Foreach is easier to identify in the template loop, and endforeach clearly indicates the end of the loop; 3. For and while are rarely used, they are also supported. This syntax has obvious advantages in view files: reduce syntax errors, enhance readability, and is similar to HTML tag structure. But curly braces should continue to be used in pure PHP files to avoid confusion. Therefore, alternative syntax is recommended in templates that mix PHP and HTML to improve code maintainability.

Thenullcoalescingoperator(??)providesaconcisewaytoassigndefaultvalueswhendealingwithnullorundefined.1.Itreturnstheleftoperandifitisnotnullorundefined;otherwise,itreturnstherightoperand.2.UnlikethelogicalOR(||)operator,??onlytriggersthefallbackfornull

Useguardclausestoreturnearlyandflattenstructure.2.Extractcomplexconditionsintodescriptivefunctionsorvariablesforclarityandreuse.3.Replacemultipleconditioncombinationswithalookuptableorstrategypatterntocentralizelogic.4.Applypolymorphismtoeliminatetyp

Sometimes it will affect performance, depending on the language, compiler optimization and logical structure; 1. If statements are executed in order, and the worst case time complexity is O(n), the most likely condition should be placed first; 2. The switch statement can be optimized by the compiler to a jump table of O(1) when the conditions are continuous integers, many branches and the values are compiled constants; 3. When a single variable is compared with multiple constant integers and there are many branches and switches are faster; 4. When it involves scope judgment, complex conditions, non-integer types or fewer branches, if if is more suitable or has similar performance; 5. Different languages (such as C/C, Java, JavaScript, C#) have different optimization degrees of switches, and they need to be tested in combination with actual testing; Swi should be used first

Alwaysusestrictequality(===and!==)inJavaScripttoavoidunexpectedbehaviorfromtypecoercion.1.Looseequality(==)canleadtocounterintuitiveresultsbecauseitperformstypeconversion,making0==false,""==false,"1"==1,andnull==undefinedalltrue.2

Use&&toskipexpensiveoperationsandguardagainstnull/undefinedbyshort-circuitingonfalsyvalues;2.Use||tosetdefaultsefficiently,butbewareittreatsallfalsyvalues(like0)asinvalid,soprefer??fornull/undefinedonly;3.Use&&or||forconciseconditiona
