?.
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
undefinedwhen the value before?.isnullorundefined.
Example
#const emma = { name: 'Emma', address: { city: 'Boston' } }
const guest = { name: 'Guest' }
console.log(emma.address?.city)
console.log(guest.address?.city)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
#object?.property
object?.[expression]
function?.(args)More examples
#function finishLesson(onFinish) {
console.log('Lesson complete')
onFinish?.('Earned 15 XP')
}
finishLesson((message) => console.log(message))
finishLesson()const response = { data: { students: [] } }
const firstName = response.data?.students?.[0]?.name ?? 'No students'
console.log(firstName)const user = null
console.log(user?.profile.nickname.toUpperCase())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 tonullandundefined. An empty string,0, orfalseare treated as ordinary values.
Related entries
#- ??The ?? (nullish coalescing) operator returns the right side only when the left side is null or undefined. Ideal for default values.
- &&, ||, !The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
- typeofReturns a string with the name of a value’s type, e.g. "number", "string", or "object".
Spotted a mistake or missing an example? Write to us.