2021-07-29 some efficient operators in JS

Posted by xcasio on Mon, 03 Jan 2022 10:31:41 +0100

A new version of JavaScript will be released every year, and some operators with more convenient and efficient operations will be added. Here are some efficient magic operators.

Chain operator (?)

When using a property with a deep structure and it is impossible to determine that all parents must exist, we need to make a series of judgments, such as a data structure:

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

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

// 
const getStudentDetil = async () => {
    const studentDetilRes = await GetStudentData({});
    setStudentData(studentDetilRes?.detail);
};

When the optional chain operator encounters null or undefined on the link, it will directly return undefined without throwing an error exception

Get deep-seated properties
console.log(student?.score?.math);
Perform an optional method

At the same time, it can also be used when executing a possible function

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

  return <div></div>;
};

Or we can use it when we execute a method of a dom element.
document.querySelector will return two types. It will return the dom element when it really exists, otherwise it will return null. When we want to call a method, we must always first 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
}

// Use the optional chain operator to transfer directly
document.querySelector('.score')?.getBoundingClientRect();
Gets the value in the array

If the array exists, get the value of a subscript. Now we don't need to judge whether the array exists. We can directly use: arr [1]
If a structure is complex and has various types, here we need to execute the method of array math subscript 2:

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

// implement 👇
student?.score?.math?.[2]?.(); // 99
The assignment operation cannot be performed

Optional chain operators can only perform acquisition operations and cannot perform 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.

Assignment operation of or operation (|) and and and operation (& &)

score = score || 1;
age = age && 18;

// It can be abbreviated as:
score ||= 1; // Equivalent to score = score | 1
age &&= 18; // Equivalent to age = age & & 18

Double question mark operator (?)

Double question mark operator??, I understand that it is designed to solve the or operator.
Or operator | -- > when the data on the left is false (number 0, Boolean false, empty string, undefined, null), the statement on the right is executed
Double question mark operator? – > The statement on the right side will be executed only when the left side is undefined or null

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

// However, in some cases, false and 0 are normal values, but using the or operator will lead to errors.

// When score is empty, the default value is 1. When a normal value of 0 is entered, 0 should be returned (but 1 is actually returned):
const getSCore = (score: number) =>{
    return score || 1;
};
getScore(0); // 1

// Double question mark operator?? The double question mark operator will execute the statement on the right only when 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 form an assignment operation. When the left is null or undefined, the result of the statement on the right is assigned to the variable on the left: score= 1; // one

Null assignment operator (? =)

Related to non airlift operators, this assignment operator assigns values only when the value is null or undefined.

let x = null
let y = 5
console.log(x ??= y) // => 5 
console.log(x = (x ?? y)) // => 5

//Difference between null assignment operator and function default value:
function getScore1(options) {
    options.math ??= 1;
    options.assess ??= 'easy';
    return options;
}
function getScore2(math=1, assess='easy') {
    return {math, assess};
}
getScore1({math: null, assess: null}) // {speed: 1, diff: 'easy'}
getScore2(undefined, null) // {speed: 1, diff: null}

Double star operator (* *)

Equals the double star in the * operator (math. js) Pow (), which performs a power operation

1 ** 2ï¼› // 1
2 ** 4ï¼› // 4th power of 2 = = math pow(2,4);

When we have babel to help transform, we can properly use these operators in the code, which can greatly simplify our code

This article borrows WeChat official account, "front end small teahouse".
Non original

Topics: Javascript Front-end TypeScript