Summary of some efficient magic operators in JS

Summary of some efficient magic operators in JS

JavaScript now releases a new version every year, which also adds some new operators that are more convenient and efficient. Today we will take stock of several efficient magic operators.

1. Optional Chaining Operator

Previously, when we wanted to use a property with a deeper structure and could not be sure that all parents existed, we needed to make a series of judgments, such as a data structure:

const student = {
  score: {
    math: 98,
  },
};

When we want to get the value of the innermost math attribute:

if (student && student.score) {
  console.log(student.score.math);
}

1.1 Get deep properties

However, when we use the optional chaining operator, the judgment becomes much simpler. When the optional chaining operator encounters null or undefined in the chain, it will directly return undefined without throwing an error exception:

console.log(student?.score?.math);

1.2 Executing an optional method

It can also be used when executing a possible function. For example, in a react component, the passed method is optional:

// getScore is an optional parameter, either undefined or a function const Student = ({ getScore }: { getScore?: () => void }) => {
  useEffect(() => {
    // When getScore exists, execute the getScore() method normally getScore?.();
  }, []);

  return <div></div>;
};

Or we can also use it when we execute a method of a DOM element.

document.querySelector returns two types. When the DOM element actually exists, it returns the element, otherwise it returns null. Anyone who has written typescript knows that when we want to call a method, we always have to make sure that the DOM element exists:

const dom = document.querySelector('.score');
if (dom) {
  dom.getBoundingClientRect(); //This method is executed only when the dom element exists}

When using the optional chaining operator, just call it directly:

document.querySelector('.score')?.getBoundingClientRect();

1.3 Get the value in the array

If the array exists, get the value of a certain index. We no longer need to determine whether the array exists, and can directly use:

arr?.[1]; // If arr exists, get the value in arr[1] normally

The above three situations can also be used in combination. If a structure is more complex, there are various types. Here we need to execute the array math subscript 2 method:

const student = {
  score: {
    math: [
      98,
      67,
      () => {
        return 99;
      },
    ],
  },
};

implement:

student?.score?.math?.[2]?.(); // 99

Is there such an operation?

1.4 Unable to perform assignment operation

The optional chaining operator can only perform get operations, not assignment operations.

For example, when assigning a value to a possible array or DOM element, a syntax exception will be thrown directly:

arr?.[1] = 2; // x
document.querySelector('.score')?.innerHTML = 98; // x

When we execute the above statement, the following prompt will be thrown:

Uncaught SyntaxError: Invalid left-hand side in assignment

That is, the optional chain on the left cannot be assigned a value.

2. Double question mark operator

The double question mark operator ??, as I understand it, is designed to solve the OR operator ||.

Let's first review the operation of the or operator. When the data on the left is a false value (the number 0, Boolean type false, empty string, undefined, null), the statement on the right is executed.

false || 123;
0 || 123;
'' || '123';
undefined || 123;
null || 123;

However, in some cases, false and 0 are both normal values, but using the or operator will result in an error.

For example, in the following example, when score is empty, the default value is 1. When the normal value 0 is entered, it should return 0 (but it actually returns 1):

const getSCore = (score: number) => {
  return score || 1;
};

getScore(0); // 1

At this time, we use the double question mark operator??. The double question mark operator will only execute the statement on the right side if the left side is undefined or null.

const getSCore = (score: number) => {
  return score ?? 1;
};

getScore(0); // 0

At the same time, the double question mark operator can also be combined with = to become an assignment operation. When the left side is null or undefined, the result of the statement on the right side is assigned to the variable on the left side:

score ??= 1; // 1

I read a lot, I won't lie to you

3. Assignment operations of OR and AND

When we used the or operator to perform assignment operations before, we wrote it like this:

score = score || 1;
age = age && 24;

Now it can be shortened to:

score ||= 1; // equivalent to score = score || 1
age &&= 24; // equivalent to age = age && 24

4. Double asterisk operator

The double asterisk operator ** was introduced into js relatively early, but we rarely use it. In fact, it performs a power operation, which is equivalent to Math.pow().

2 ** 10; // 1024, 2 to the power of 10, equivalent to Math.pow(2, 10);

5. Conclusion

All the above samples have been run successfully on Chrome 90.

If we already have Babel to help convert, we can appropriately apply these operators in the code, which can greatly simplify our code.

This concludes this article about the summary of some efficient operators in JS. For more relevant JS efficient operators, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript operators explained in detail never before
  • Summary of uncommon js operation operators
  • JavaScript Basics Operators
  • Summary of uncommon operators and operators in js
  • Stop using absolute equality operators everywhere in JS
  • Let's take a look at the same old JS operator explanation

<<:  Use of Linux dynamic link library

>>:  How to set mysql permissions using phpmyadmin

Recommend

Implementation and optimization of MySql subquery IN

Table of contents Why is IN slow? Which is faster...

A brief discussion on mysql backup and restore for a single table

A. Installation of MySQL backup tool xtrabackup 1...

MySQL data aggregation and grouping

We often need to summarize data without actually ...

How to install MySQL and MariaDB in Docker

Relationship between MySQL and MariaDB MariaDB da...

Chrome plugin (extension) development guide (complete demo)

Table of contents Written in front Preface What i...

Solve the conflict between docker and vmware

1. Docker startup problem: Problem Solved: You ne...

Implementation of building custom images with Dockerfile

Table of contents Preface Introduction to Dockerf...

Vue implements click feedback instructions for water ripple effect

Table of contents Water wave effect Let's see...

Introduction to JWT Verification Using Nginx and Lua

Table of contents Preface Lua Script nignx.conf c...

Detailed tutorial on installing Spring boot applications on Linux systems

Unix/Linux Services systemd services Operation pr...

Introducing the code checking tool stylelint to share practical experience

Table of contents Preface text 1. Install styleli...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

Reduce memory and CPU usage by optimizing web pages

Some web pages may not look large but may be very ...