?.

The ?. (optional chaining) operator safely reads a property. When the object is null or undefined, it returns undefined instead of throwing.

Returns
The value of the property, or the result of the call, or undefined when the value before ?. is null or undefined.
On this page

Example

#
JavaScript
const emma = { name: 'Emma', address: { city: 'Boston' } }
const guest = { name: 'Guest' }

console.log(emma.address?.city)
console.log(guest.address?.city)
Console
Boston
undefined

Definition and usage

#

The ?. operator checks the value on its left side. If it’s null or undefined, the whole expression immediately evaluates to undefined. Otherwise it works like a plain dot.

It solves a common problem with data that might be incomplete, like an API response. Instead of user && user.address && user.address.city, you just write user?.address?.city. It also works with square brackets, obj?.[key], and with a function call, callback?.(), which only runs the function if it exists.

The operator short-circuits the rest of the chain: if user is null, the remaining part of user?.profile.name never runs at all. You can’t use it on the left side of an assignment, and reading an undeclared variable still throws a ReferenceError.

Syntax

#
Syntax
object?.property
object?.[expression]
function?.(args)

More examples

#
Calling an optional function
JavaScript
function finishLesson(onFinish) {
  console.log('Lesson complete')
  onFinish?.('Earned 15 XP')
}

finishLesson((message) => console.log(message))
finishLesson()
Console
Lesson complete
Earned 15 XP
Lesson complete
An array index and a fallback value
JavaScript
const response = { data: { students: [] } }

const firstName = response.data?.students?.[0]?.name ?? 'No students'
console.log(firstName)
Console
No students
Short-circuiting the whole chain
JavaScript
const user = null

console.log(user?.profile.nickname.toUpperCase())
Console
undefined

When user is null, the rest of the chain isn’t evaluated, so the missing ?. before profile doesn’t cause an error. But if user were an object without a profile, reading .nickname would throw a TypeError.

Browser support

#

Widely available

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

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t sprinkle ?. everywhere “just in case.” Use it where a missing value is normal. If an object should always exist, an error helps you find the problem faster.
  • Combine ?. with ?? to supply a fallback value right away: user?.nickname ?? "Anonymous".
  • ?. only reacts to null and undefined. An empty string, 0, or false are treated as ordinary values.

Related entries

#

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