The nullish coalescing operator (??) in JavaScript
- Authors
- 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 valueRelated
The double exclamation mark (!!) is often confused with ?? but does something different: it converts a value to a boolean. See understanding !! in JavaScript.
Related articles
Check if a string is alphanumeric in JavaScript
How to check if a string is alphanumeric in JavaScript using a regular expression, including a reusable helper and notes on empty strings and Unicode.
Force an LLM to return JSON in JavaScript
Return schema-shaped JSON from an LLM in JavaScript using OpenAI structured outputs instead of fragile JSON parsing.
LangChain JS agent with a custom tool
Create a small LangChain JavaScript agent with one custom tool using createAgent, tool, and Zod.

