


Detailed explanation of JavaScript's null value coalescing operator (??)
This article will introduce you to JavaScript’s null value merging operator (??). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
This year ECMAScript 2020 (ES2020) will be released! Since the release of ECMAScript 2015 (ES6) in 2015, we have updated the JavaScript language every year.
Directory
- Using JavaScript null value coalescing operator
- Usage example
- null Value combining operator with logical OR (
||
) - Browser support
- Summary
In ES2020, we got Features that have long been available in other languages such as C# and PHP: Null Coalescing Operator. I've always liked this name because I feel smart every time I say it.
The null value coalescing operator will traverse the list and return the first value that is not null or undefined.
It is important to note that the null coalescing operator only looks for null
or null
values. The null coalescing operator accepts falsy values (Falsy values).
Using the JavaScript null coalescing operator (??)
Let’s look at some examples. Remember that JavaScript's null coalescing operator will follow a ??
chain until a non-null or undefined object is found. If false
is found, it will return that value.
null ?? 'hi' // 'hi' undefined ?? 'hey' // 'hey' false ?? 'hola' // false 0 ?? 'bonjour' // 0 'first' ?? 'second' // first
In the following example, we store some values in a variable:
let person // <-- person is undefined here person ?? { name: 'chris' } // { name: 'chris' } const isActive = false isActive ?? true // false
Linking JavaScript’s null value coalescing operator
The great thing about JavaScript’s null coalescing operator is that we can chain it as many times as we need.
null ?? undefined ?? false ?? 'hello' // false null ?? '' ?? 'hello' // ''
Usage Example
Can be used when getting data from external sources. For example, we want to crawl blog articles from multiple places. You can then determine which post will become our featured post:
// 简化代码。 使用 fetch requires 需要比这更多的代码 const firstBlogPost = await fetch('...') const secondBlogPost = await fetch('...') const defaultBlogPost = { title: 'Default Featured Post' } const featuredBlogPost = firstBlogPost ?? secondBlogPost ?? defaultBlogPost
The above is a good way to set default values if you're not sure whether certain values exist.
Empty coalescing operator and logical OR (<span style="font-size: 18px;">||</span>
)
If you want to eliminate For virtual values, you can use the logical OR operator (||
).
Essentially, it does the same thing as the null coalescing operator, except that it eliminates imaginary values.
- The null value coalescing operator will skip
null
,undefined
- The logical OR operator will skip
null
,undefined
,false
false ?? 'hello' // false false || 'hello' // 'hola'
If you don’t want to use virtual values, you can use ||
. If you just want to check if it is null
or undefined
, use ??
.
Browser Support
As of this writing, the null coalescing operator is available in the latest versions of Chrome, Firefox, Edge, and Safari.
Summary
The null coalescing operator is a nice addition to the JavaScript language. It doesn't hurt to have options with more check values.
English original address: https://scotch.io/tutorials/javascripts-null-coalescing-operator
Author: Chris on Code
Translation address: https://segmentfault.com/a/1190000023577464
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of Detailed explanation of JavaScript's null value coalescing operator (??). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

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











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

The += operator is used to add the value of the left operand to the value of the right operand and assign the result to the left operand. It is suitable for numeric types and the left operand must be writable.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Introduction to python operators Operators are special symbols or keywords used to perform operations between two or more operands. Python provides a variety of operators covering a wide range of uses, from basic mathematical operations to complex data manipulation. Mathematical operators Mathematical operators are used to perform common mathematical operations. They include: operator operation examples + addition a + b - subtraction a-b * multiplication a * b / division a / b % modulo operation (take the remainder) a % b ** power operation a ** b // integer division (discard the remainder) a//b Logical Operators Logical operators are used to concatenate Boolean values and evaluate conditions. They include: operator operations examples and logical and aandbor logical or aorbnot logical not nota comparison operations
