What is optional chaining (?.) in JS?
Optional chaining (?.) in JavaScript safely accesses nested properties by returning undefined if any part of the chain is null or undefined, preventing runtime errors. 1. It allows safe access to deeply nested object properties, such as user.profile?.settings?.theme. 2. It enables calling methods that may not exist, like obj.someMethod?.(). 3. It supports safe array element access, e.g., users[0]?.name. 4. It works with dynamic property keys, such as user.contact?.[key]. However, it cannot be used on the left-hand side of assignments, and should be combined with nullish coalescing (??) for default values, as in user.preferences?.theme ?? 'light'. This feature is especially useful when handling incomplete or unpredictable data from APIs or configurations.

Optional chaining (?.) in JavaScript is a feature introduced in ES2020 that lets you safely access nested object properties without having to explicitly check if each reference in the chain is valid (i.e., not null or undefined).

How It Works
The ?. operator stops evaluating and returns undefined as soon as it encounters a null or undefined value in the property chain. This prevents runtime errors like "Cannot read property of undefined."
Example Without Optional Chaining:
const user = { name: "John", address: null };
// Without optional chaining, this would throw an error:
const city = user.address.city; // TypeError: Cannot read property 'city' of nullWith Optional Chaining:
const city = user.address?.city; // undefined — no error console.log(city); // Output: undefined
It only checks whether the value before ?. is null or undefined, and if so, returns undefined immediately.

Common Use Cases
1. Accessing Nested Object Properties
const user = { profile: { settings: { theme: 'dark' } } };
// Safe access
const theme = user.profile?.settings?.theme; // 'dark'
const language = user.profile?.preferences?.lang; // undefined (no error)2. Calling Methods That Might Not Exist
const obj = {
someMethod() {
return "Hello";
}
};
// Safe method call
obj.someMethod?.(); // "Hello"
obj.missingMethod?.(); // undefined — no error3. Accessing Array Elements Safely
const users = [{ name: "Alice" }, { name: "Bob" }];
users[0]?.name; // "Alice"
users[5]?.name; // undefined — no error4. With Dynamic Property Keys
const key = 'email'; const email = user.contact?.[key]; // Safe dynamic access
Important Notes
- Optional chaining only works for reading/invoking. You can’t use it on the left-hand side of an assignment.
user?.name = "John"; // ❌ SyntaxError
- It’s not a replacement for proper data validation — it just prevents crashes during access.
- Always pair it with fallbacks when needed:
const theme = user.preferences?.theme ?? 'light'; // default to 'light'
Basically,
?.makes your code safer and cleaner when dealing with uncertain object structures. It’s especially useful when working with APIs, configuration objects, or deeply nested data where some parts might be missing.The above is the detailed content of What is optional chaining (?.) in JS?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Advanced Conditional Types in TypeScript
Aug 04, 2025 am 06:32 AM
TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3
Micro Frontends Architecture: A Practical Implementation Guide
Aug 02, 2025 am 08:01 AM
Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents
How to find the length of an array in JavaScript?
Jul 26, 2025 am 07:52 AM
To get the length of a JavaScript array, you can use the built-in length property. 1. Use the .length attribute to return the number of elements in the array, such as constfruits=['apple','banana','orange'];console.log(fruits.length);//Output: 3; 2. This attribute is suitable for arrays containing any type of data such as strings, numbers, objects, or arrays; 3. The length attribute will be automatically updated, and its value will change accordingly when elements are added or deleted; 4. It returns a zero-based count, and the length of the empty array is 0; 5. The length attribute can be manually modified to truncate or extend the array,
What are the differences between var, let, and const in JavaScript?
Aug 02, 2025 pm 01:30 PM
varisfunction-scoped,canbereassigned,hoistedwithundefined,andattachedtotheglobalwindowobject;2.letandconstareblock-scoped,withletallowingreassignmentandconstnotallowingit,thoughconstobjectscanhavemutableproperties;3.letandconstarehoistedbutnotinitial
Understanding JavaScript's Proxy and Reflect APIs
Jul 26, 2025 am 07:55 AM
Proxy and Reflect API are powerful tools used in JavaScript to intercept and customize object operations; 1. Proxy blocks operations such as get, set by wrapping target objects and defining "traps", and implements functions such as logs, verification, read-only control; 2. Reflect provides methods corresponding to Proxy traps to ensure the consistency and correctness of default behaviors and improve code maintainability; 3. Practical applications include Vue3 responsive system, data verification, debug logs, immutable objects and API simulation; 4. Pay attention to performance overhead, complex behavior of built-in objects, this binding problems, and nested objects need to be recursively proxyed; 5. Reasonable use can build efficient, debugable, and reactive
Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms
Aug 05, 2025 am 08:30 AM
This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.
What is optional chaining (?.) in JS?
Aug 01, 2025 am 06:18 AM
Optionalchaining(?.)inJavaScriptsafelyaccessesnestedpropertiesbyreturningundefinedifanypartofthechainisnullorundefined,preventingruntimeerrors.1.Itallowssafeaccesstodeeplynestedobjectproperties,suchasuser.profile?.settings?.theme.2.Itenablescallingme
How can you remove a CSS class from a DOM element using JavaScript?
Aug 05, 2025 pm 12:51 PM
The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList


