??= 賦值操作僅在左側(cè)為 null 或 undefined 時(shí)生效,1. 用于設(shè)置默認(rèn)配置值,如 user.age ??= 18;2. 實(shí)現(xiàn)變量的惰性初始化,如 cache ??= initializeHeavyResource();3. 合并可選對象屬性時(shí)保留有效值,如 userData.email ??= getDefaultEmail();該操作符不會(huì)覆蓋 0、'' 或 false 等 falsy 值,比 ||= 更安全,適用于現(xiàn)代環(huán)境,最終使代碼更簡潔、安全且可預(yù)測。
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 falsy 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 falsy value (0
,''
,false
, etc.), which can lead to bugs.??=
is safer 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
→ kept 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 applies:
// 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 falsy 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 falsy" — often too aggressive
With ??=
, your code becomes cleaner, safer, and more predictable when handling optional values.
以上是利用無效的合并分配操作員(`?? =`)的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

使用===而非==是避免PHP類型轉(zhuǎn)換錯(cuò)誤的關(guān)鍵,因?yàn)?=會(huì)進(jìn)行類型轉(zhuǎn)換導(dǎo)致意外結(jié)果,而===同時(shí)比較值和類型,確保判斷準(zhǔn)確;例如0=="false"為真但0==="false"為假,因此在處理可能為0、空字符串或false的返回值時(shí)應(yīng)使用===來防止邏輯錯(cuò)誤。

thenullcoalescoleserator(??)提供AconCiseWayDoAssignDefaultValuesWhenDeAlingWithNullOundEndined.1.ItreturnStheTheStheStheStheLsthelefterftoperandifitisnotNullOndined nullOndined;否則,ittReturnTherStherStherStherStherStherStherStherStherStherightoperand.2.unlikethelogicalor(| nlikethelogicalor(

PHP的替代控制結(jié)構(gòu)使用冒號(hào)和endif、endfor等關(guān)鍵字代替花括號(hào),能提升混合HTML時(shí)的可讀性。1.if-elseif-else用冒號(hào)開始,endif結(jié)束,使條件塊更清晰;2.foreach在模板循環(huán)中更易識(shí)別,endforeach明確標(biāo)示循環(huán)結(jié)束;3.for和while雖較少用但同樣支持。這種語法在視圖文件中優(yōu)勢明顯:減少語法錯(cuò)誤、增強(qiáng)可讀性、與HTML標(biāo)簽結(jié)構(gòu)相似。但在純PHP文件中應(yīng)繼續(xù)使用花括號(hào)以避免混淆。因此,在PHP與HTML混合的模板中推薦使用替代語法以提高代碼可維護(hù)性。

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

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

有時(shí)會(huì)影響性能,具體取決于語言、編譯器優(yōu)化和邏輯結(jié)構(gòu);1.if語句按順序執(zhí)行,最壞情況時(shí)間復(fù)雜度為O(n),應(yīng)將最可能成立的條件放在前面;2.switch語句在條件為連續(xù)整數(shù)、分支較多且值為編譯時(shí)常量時(shí)可被編譯器優(yōu)化為O(1)的跳轉(zhuǎn)表;3.當(dāng)比較單一變量與多個(gè)常量整數(shù)且分支較多時(shí)switch更快;4.當(dāng)涉及范圍判斷、復(fù)雜條件、非整型類型或分支較少時(shí)if更合適或性能相當(dāng);5.不同語言(如C/C 、Java、JavaScript、C#)對switch的優(yōu)化程度不同,需結(jié)合實(shí)際測試;應(yīng)優(yōu)先使用swi

使用&& toskipexpedialoperations和guardagagainstnull/undefinedByshort-circuitingOnfalsyValues; 2.使用|| || tosetDefaultSeflsefelse,butbewareittreatsallfalteatsallfalsyvalues(like0)asoprefer fornull/undefineononly; 3. use; forsecon; 3. use; forsecon; 3. usecon;
