Take stock of some powerful operators in JavaScript

  • 2021-12-05 05:13:21
  • OfStack

Preface to the catalogue 1.? ? Null value merge operator 2.? ? = Null assignment operator 3.? Optional chain operator 4.? 3-ary operator 5. Logic and ( & & ) and logical or () 6. Bitwise operators & And 7. Two-bit operators ~ ~ 7. Logical operators! 7.1 Use! Take inverse 7.2 and use it! ! Make a summary of type judgment 7.3 whether two values are equal

Preface

When you are reading other people's codes, have you met some strange writing methods, which make your thoughts get stuck instantly? When you come to your senses, you don't know that a certain warrior has been here.

Today, let's take a look at some powerful operators in JavaScript ~ ~ ~

1.? ? Null value merge operator

If you meet it for the first time, you see two question marks, and it is estimated that there are more question marks in your mind (children, do you have many question marks ~ ~ ~)

Two question marks? ? Its beautiful name is null value merge operator. If the first parameter is not null/undefined, it will return the first parameter, otherwise it will return the second parameter.


console.log(1 ?? "www.shanzhzonglei.com"); // 1
console.log(false ?? "www.shanzhzonglei.com"); // false
console.log(null ?? "www.shanzhzonglei.com"); // www.shanzhzonglei.com
console.log(undefined ?? "www.shanzhzonglei.com"); // // www.shanzhzonglei.com

Therefore, the second parameter is returned only if the first parameter is null/undefined.

Note that although the undefined undefined, the empty object null, the numeric value 0, the empty number NaN, the Boolean false, and the empty string ''in JS are all false values, but? ? The non-null operator only handles null/undefined.

Unlike the logical OR operator (), which returns the right-hand operand when the left-hand operand is false. For example, when it is a false value (''or 0).


console.log(1 || 2); // 1
console.log("" || 2); // 2

2.? ? = Null assignment operator

Oh, now there are more than two question marks and one more equal sign. Is the topic getting harder and harder?

? ? = Null assignment operator, which is assigned only when the value is null or undefined.


const student = { age: 20 };
student.age ??= 18;
console.log(student.age); // 20

student.name ??= "shanguagua";
console.log(student.name); // 'shanguagua'

It and the one on it? ? The null value merge operator is related: x? ? = y is equivalent to x? ? (x = y), x = y is executed only if x is null or undefined.


let x = null;
x ??= 20;
console.log(x); // 20

let y = 5;
y ??= 10;
console.log(y); // 5

3.? Optional chain operator

Optional chain operator? Allows the value of a property located deep in the chain of connected objects to be read without explicitly verifying that each reference in the chain is valid. The operator implicitly checks whether the property of the object is null or undefined, which makes the code more elegant and concise.


const obj = {
  name: " Mountain croak ",
  foo: {
    bar: {
      baz: 18,
      fun: () => {},
    },
  },
  school: {
    students: [
      {
        name: "shanguagua",
      },
    ],
  },
  say() {
    return "www.shanzhonglei.com";
  },
};

console.log(obj?.foo?.bar?.baz); // 18
console.log(obj?.school?.students?.[0]["name"]); // shanguagua
console.log(obj?.say?.()); // www.shanzhonglei.com

4.? 3-ary operator

It is also called the 3-item operator. Well, this is very common.

For the conditional expression b? x: y, first calculate the condition b, and then make a judgment. If the value of b is true, the value of x is calculated, and the calculation result is the value of x; Otherwise, the value of y is calculated, and the result is the value of y.


console.log(false ? 1 : 2); // 2
console.log(true ? 1 : 2); // 1

5. Logic and ( & & ) and logical or ()

Let's review one time first:

Logical and ( & & ): When the first operand is true, the second operand will not be judged because the final result of the operation 1 is true regardless of the second operand.

In actual development, the following operations can be realized by using a feature:

1. If a value is true, run an function


function say() {
  console.log("www.shanzhonglei.com");
}
let type = true;
type && say(); // www.shanzhonglei.com

2. Judge a certain value


//  If age Greater than 10 And less than 20 Will be executed 
if (age > 10 && age < 20) {
  console.log(age);
}

Logical OR (): When the first operand is false (that is, the false value of js), the second operand will not be judged, because no matter what the second operand is, the final operation result 1 will be false.

In actual development, the following operations can be realized by using a feature:

1. Set an initial value for a variable


let student = {
  name: "shanguagua",
};

console.log(student.age || "www.shanzhonglei.com"); // www.shanzhonglei.com

2. Judge a certain value


//  If age Equal to 10 Or equal to 20 Or equal to 30 Execute both 
if (age === 10 || age === 20 || age === 30) {
  console.log(age);
}

6. Bitwise operators & And

Bitwise operators operate on a bitwise basis, & (and), (or), decimal places are discarded when using bit operators, and we can use 0 to round numbers. You can also use the & 1 to judge the odd and even number.

In actual development, the following operations can be realized by using a feature:

1. Rounding


console.log(1 || 2); // 1
console.log("" || 2); // 2
0

2. Judge the odd and even number


console.log(1 || 2); // 1
console.log("" || 2); // 2
1

7. Two-bit operators ~ ~

You can use two-bit operators instead of positive Math. floor () and negative Math. ceil ().

The advantage of the double negative bit operator is that it runs faster to perform the same operation, and the ~ ~ operation results in the same way as Math. floor () for positive numbers and the same way as Math. ceil () for negative numbers.


console.log(1 || 2); // 1
console.log("" || 2); // 2
2

7. Logical operators!

! You can convert variables to type boolean, null, undefined, and the empty string ''inverted are all true, and the rest are false. Generally speaking, there are several usages. ,! ! ,! =,! = =.

7.1 Use! Inversion


let cat = false;
console.log(!cat); // true

7.2 Use! ! Make type judgment

Determine that the variable a is not equal to null, undefined, and ''to execute the method.


console.log(1 || 2); // 1
console.log("" || 2); // 2
4

Equivalent to:


console.log(1 || 2); // 1
console.log("" || 2); // 2
5

7.3 Are two values equal

1 Generally speaking, all of them are not equal to each other! = =, because using is not equal! =, 0! = "" Returns false, because both 0 and ''in JS are converted to Boolean false, so it is recommended to use all not equal! = =.


console.log(1 || 2); // 1
console.log("" || 2); // 2
6

Summarize


Related articles: