??
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
nullorundefined, otherwise the right value.
Example
#const savedVolume = 0
const savedName = null
console.log(savedVolume ?? 50)
console.log(savedVolume || 50)
console.log(savedName ?? '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
#leftExpr ?? rightExpr
target ??= valueMore examples
#function createGame(options) {
return {
lives: options.lives ?? 3,
hints: options.hints ?? true,
level: options.level ?? 1
}
}
console.log(createGame({ lives: 0, hints: false }))const profile = { name: 'Jack', avatar: null }
profile.avatar ??= 'default.png'
profile.name ??= 'Anonymous'
console.log(profile)const nickname = ''
const fallback = null
const label = (nickname || fallback) ?? 'Anonymous'
console.log(label)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 forundefined, while??also handlesnull. Pick the tool that matches the data you’re getting.
Related entries
#- ?.The ?. (optional chaining) operator safely reads a property. When the object is null or undefined, it returns undefined instead of throwing.
- &&, ||, !The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.
- ? :The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
Spotted a mistake or missing an example? Write to us.