This is the second day of my participation in the August Text Challenge.More challenges in August

A new version of JavaScript comes out every year, with new operators that make it easier and more efficient to operate. Here are a few more efficient operators.

Chain operators (?)

We need to make a series of judgments when using a deeply structured property without being sure that all the parents must exist, such as a data structure:

const student = {
  score: {
    math: 98,}};if (student && student.score) {
  console.log(student.score.math);
}

// 
const getStudentDetil = async() = > {const studentDetilRes = awaitGetStudentData({}); setStudentData(studentDetilRes? .detail); };Copy the code

The optional chain operator returns undefined when null or undefined is encountered on the link without throwing an error exception.

Get deep attributes

console.log(student? .score? .math);Copy the code

Execute an optional method

It can also be used when executing a function that might exist

// getScore is an optional argument, either undefined or a function
const Student = ({ getScore }: { getScore? : () = >void }) = > {
  useEffect(() = >{ getScore? . ();// The getScore() method is normally executed when getScore exists} []);return <div></div>;
};
Copy the code

Or when we execute a method on a DOM element. Document. querySelector returns two types, the DOM element if it actually exists and null otherwise. When we call a method, we always make sure that the DOM element exists:

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

// The optional chain operator can be used directly
document.querySelector('.score')? .getBoundingClientRect();Copy the code

Gets the value in the array

If the array exists, we get the value of some index. Instead of checking whether the array exists, we can simply use: arr? [1] If a structure is complex and there are multiple types, here we call the array math subscript 2 method:

const student = {
  score: {
    math: [98.67.() = > {
        return 99; },],}};/ / 👇 executionstudent? .score? .math? .2]? . ();/ / 99
Copy the code

Unable to perform assignment

Optional chain operators can only perform fetches, not assignments. For example, assigning a value to an array or DOM element throws a syntax exception:

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

When we execute the above statement, the following prompt is thrown:

Uncaught SyntaxError: Invalid left-hand side in assignment

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

Double question mark operator (??)

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

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

There are cases, however, where false and 0 are both normal values, but using the or operator results in an error.

// When score is empty, the default value is 1. It should return 0 when entering a normal value of 0 (but it actually returns 1) :
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 if the left side is undefined or null.
const getSCore = (score: number) = >{
    return score ?? 1;
};
getScore(0); / / 0
Copy the code

The double question mark operator can also be combined with = to form an assignment. 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: score?? = 1; / / 1

The null assignment operator (?? =)

Associated with a non-air operator, this assignment operator assigns only if the value is null or undefined.

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

// The difference between the null assignment operator and the function default:
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}
Copy the code

Double star operator (**)

The double star operator ** (exponentiation operator) is equivalent to math.pow () in JS, which performs a power operation

1支那2;/ / 1
2支那4;// The 4th power of 2 == "math.pow (2,4);
Copy the code

Or operation (| |) and operation (&&) assignment operation

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

// Can be shortened to:
score ||= 1; / / equivalent score = score | | 1
age &&= 18; // Equivalent to age = age &&18
Copy the code

Some other operators

JavaScript arithmetic operator

+ addition – subtraction * multiplication/division % mod (remainder) ++ increment-decrement

JavaScript type operator

  • typeofReturns the type of the variable.
  • instanceofReturns true if the object is an instance of the object type.

Comma operator

The same operator that we often use for assignment is —- and the comma operator 😂, which is often used in variable declarations, can perform multiple operations in a single statement

var num = 1, num2 = 2, num3 = 3;
Copy the code

Using these operators properly in our code with the help of Babel can greatly simplify our code