The nullish coalescing operator (??) in JavaScript

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
2 mins read

The double question mark (??) is the nullish coalescing operator. It returns the right-hand value only when the left-hand value is null or undefined, and otherwise returns the left-hand value. It is the cleanest way to supply a default.

const name = userInput ?? 'Anonymous'
// 'Anonymous' only if userInput is null or undefined

?? vs ||

This is the part that trips people up. The OR operator (||) falls back on any falsy value: 0, '', false, NaN, null, and undefined. The nullish operator (??) falls back only on null and undefined, so valid values like 0 and an empty string are kept.

const count = 0
count || 10 // 10 (0 is falsy, so || replaces it)
count ?? 10 // 0 (0 is a real value, so ?? keeps it)

Use ?? when 0, '', or false are legitimate values you do not want to overwrite. Use || when any falsy value should trigger the default.

The ??= assignment shorthand

??= assigns only if the variable is currently null or undefined. It is a shorter way to set a default on an existing variable or property.

const settings = { theme: null }
settings.theme ??= 'light'
settings.theme // 'light'
settings.theme ??= 'dark'
settings.theme // still 'light', because it already had a value

The double exclamation mark (!!) is often confused with ?? but does something different: it converts a value to a boolean. See understanding !! in JavaScript.