国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Optional Chaining solves deep access problems
Nullish Coalescing provides more accurate default values
Better use with
Home Web Front-end JS Tutorial Using Javascript Optional Chaining and Nullish Coalescing

Using Javascript Optional Chaining and Nullish Coalescing

Jul 07, 2025 am 01:35 AM

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.

Using Javascript Optional Chaining and Nullish Coalescing

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.

Using Javascript Optional Chaining and Nullish Coalescing

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:

Using Javascript Optional Chaining and Nullish Coalescing
 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.

Using Javascript Optional Chaining and Nullish Coalescing

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

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.

Mastering JavaScript Comments: A Comprehensive Guide Mastering JavaScript Comments: A Comprehensive Guide Jun 14, 2025 am 12:11 AM

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

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

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

JavaScript Data Types: A Deep Dive JavaScript Data Types: A Deep Dive Jun 13, 2025 am 12:10 AM

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

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

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.

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

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

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

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

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

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

See all articles