Table of Contents
Using the JavaScript null coalescing operator (??) " >Using the JavaScript null coalescing operator (??)
Usage Example" >Usage Example
Empty coalescing operator and logical OR (||)" >Empty coalescing operator and logical OR (||)
Browser Support" >Browser Support
Summary" >Summary
Home Web Front-end JS Tutorial Detailed explanation of JavaScript's null value coalescing operator (??)

Detailed explanation of JavaScript's null value coalescing operator (??)

Dec 02, 2020 pm 06:02 PM
javascript 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.

Detailed explanation of JavaScript's null value coalescing operator (??)

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
Copy after login

In the following example, we store some values ​​in a variable:

let person  // <-- person is undefined here

person ?? { name: &#39;chris&#39; }       // { name: &#39;chris&#39; }

const isActive = false

isActive ?? true             // false
Copy after login

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 ?? &#39;hello&#39;     // false
null ?? &#39;&#39; ?? &#39;hello&#39;                     // &#39;&#39;
Copy after login

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(&#39;...&#39;)
const secondBlogPost = await fetch(&#39;...&#39;)
const defaultBlogPost = { title: &#39;Default Featured Post&#39; }

const featuredBlogPost = firstBlogPost ?? secondBlogPost ?? defaultBlogPost
Copy after login

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 ?? &#39;hello&#39;    // false
false || &#39;hello&#39;    // &#39;hola&#39;
Copy after login

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.

Detailed explanation of JavaScripts null value coalescing operator (??)

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!

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

Analysis of the meaning and usage of += operator in C language Analysis of the meaning and usage of += operator in C language Apr 03, 2024 pm 02:27 PM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

Python Operators: The Ultimate Guide from Newbie to Master Python Operators: The Ultimate Guide from Newbie to Master Mar 11, 2024 am 09:13 AM

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

See all articles