JavaScript's optional chaining and null value merging do not make your code more concise and safer. 1. Optional Chaining is used in the form of user?.address?.city to avoid errors caused by null or undefined when accessing nested properties, and there is no need for multiple conditions to judge; 2. Nullish Coalescing is used to provide default values ??when the value is null or undefined, and will not misjudge false values ??such as '', 0, false; 3. Use the two together, such as user?.profile?.age ?? 25, which can obtain values ??from potentially empty objects and set default values ??more safely and concisely, and is suitable for processing API data, component props, user input and other scenarios.
Combining optional chains and null values ??with JavaScript can make your code more concise and safer. These two features are mainly used to solve the problem of error-prone when accessing nested object properties and processing default values. Especially when you are not sure if an object or its properties exist, they are very useful.

Optional Chaining solves deep access problems
In JavaScript, if you try to access an object property that does not exist, such as user.address.city
, and address
is undefined
, the program will report an error. In the past, you might have to use multiple criteria to avoid this problem:

if (user && user.address && user.address.city) { // Do something}
Now that there is an optional chain, you can write it like this:
const city = user?.address?.city;
If user
or address
is null
or undefined
, the expression will directly return undefined
and will not report an error. This syntax is particularly friendly to access deep structures and reduces a lot of redundant judgment logic.

Use scenarios include but are not limited to:
- Access the nested data returned by the API
- Handle props that may not be passed in React components
- Read the browser object model (such as
window.navigator.userAgent
)
Nullish Coalescing provides more accurate default values
In the past, logic or operator ||
was commonly used to set default values, such as:
const name = username || 'Guest';
But there is a problem with this method: "false values" such as ''
, 0
, and false
will also trigger the default values. If you want the default value to be used only if the value is null
or undefined
, then you should use the null value merge operator ??
:
const name = username ?? 'Guest';
At this time, 'Guest'
will be displayed only when username
is null
or undefined
, and other false values ??will be retained.
For example:
console.log(null ?? 'default'); // 'default' console.log(undefined ?? 'default');// 'default' console.log('' ?? 'default'); // '' console.log(0 ?? 'default'); // 0
This feature is very useful in handling user input, configuration item merging and other scenarios.
Better use with
Many times you will use these two operators at the same time. For example, get a value from an object that may be empty and give a default value:
const age = user?.profile?.age?? 25;
The meaning of this code is: if user
or profile
does not exist, or age
is null
or undefined
, it returns 25. Otherwise, the actual age
value is returned.
This combination allows you to be both safe and concise when dealing with complex data structures.
Basically that's it. The rational use of optional chains and null values ??can greatly reduce the number of defensive codes and make the intention clearer. Small details that are not complicated but are easily overlooked can often improve the quality of the code.
The above is the detailed content of Using Javascript Optional Chaining and Nullish Coalescing. 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)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl
