??

The ?? (nullish coalescing) operator returns the right side only when the left side is null or undefined. Ideal for default values.

Returns
The left value, if it’s not null or undefined, otherwise the right value.
On this page

Example

#
JavaScript
const savedVolume = 0
const savedName = null

console.log(savedVolume ?? 50)
console.log(savedVolume || 50)
console.log(savedName ?? 'Guest')
Console
0
50
Guest

Definition and usage

#

The ?? operator checks the left side. If it’s null or undefined, it returns the right side. In every other case it returns the left side, even when that’s 0, an empty string "", or false.

That’s the difference from ||, which rejects every falsy value. For numbers and settings this matters: volume || 50 replaces a deliberately set 0 with 50, while volume ?? 50 leaves the 0 alone.

The right side is only evaluated when it’s actually needed. The assignment operator ??= sets a value only when a variable or property is empty: settings.lang ??= "en". When combining ?? with || or &&, you need parentheses, otherwise you get a syntax error.

Syntax

#
Syntax
leftExpr ?? rightExpr
target ??= value

More examples

#
Settings with default values
JavaScript
function createGame(options) {
  return {
    lives: options.lives ?? 3,
    hints: options.hints ?? true,
    level: options.level ?? 1
  }
}

console.log(createGame({ lives: 0, hints: false }))
Console
{ lives: 0, hints: false, level: 1 }
The ??= assignment
JavaScript
const profile = { name: 'Jack', avatar: null }

profile.avatar ??= 'default.png'
profile.name ??= 'Anonymous'

console.log(profile)
Console
{ name: 'Jack', avatar: 'default.png' }
Parentheses when combining with ||
JavaScript
const nickname = ''
const fallback = null

const label = (nickname || fallback) ?? 'Anonymous'
console.log(label)
Console
Anonymous

Writing nickname || fallback ?? "Anonymous" without parentheses is a syntax error. The parentheses make it clear what should run first.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For numbers, flags, and settings where 0, false, or "" are valid values, choose ?? over ||.
  • Default parameter values (function fn(x = 5)) and destructuring defaults only work for undefined, while ?? also handles null. Pick the tool that matches the data you’re getting.

Related entries

#

Spotted a mistake or missing an example? Write to us.