- Published on
What is the nullish coalescing operator?
- Authors
- Name
- hwahyeon
The nullish coalescing operator (??
) in JavaScript returns an alternative value only when the given value is considered null
or undefined
.
let result = value1 ?? value2
If value1
is null
or undefined
, value2
is returned. Otherwise, value1
is returned.
Here are some clearer examples:
A default message like "No data":
let result = value ?? 'No data'
If value
is null
or undefined
, "No data"
is returned.
A default numeric value:
let pageNumber = currentPage ?? 1
If currentPage
is null
or undefined
, 1
is returned.
A default object:
let settings = userSettings ?? { theme: 'dark', fontSize: 14 }
If userSettings
is null
or undefined
, the default settings object is returned.