A summary of operators and operators in JS

In JavaScript, there are operators that make code more concise, readable, and efficient. Here are some common operators:

1. Optional chaining operator

?.is an optional chaining operator . ?. The optional chaining operator is used to access properties or methods that may be null or undefined. It allows us to safely access properties of nested objects. If an intermediate property is null or undefined, an error will not be thrown, but returns undefined. For example:

const obj = {
  foo: {
    bar: 123
  }
};

// 普通访问属性的方式
const x = obj.foo.bar; // x = 123

// 使用可选链操作符
const y = obj?.foo?.bar; // y = 123

// 如果对象未定义,则返回 undefined
const z = undefined?.foo?.bar; // z = undefined

2. Nullish coalescing operator

??Is the nullish coalescing operator . ?? The null coalescing operator is used to check whether a variable is null or undefined, and if so, returns a default value, otherwise returns the value of the variable. ||Different from traditional logical operators ??, it only returns the default value on the right side when the value on the left side is null or undefined, and does not return the default value for other false values ​​(such as empty strings, 0, false, etc.), and is returns itself. For example:

const x = undefined ?? 'default'; // x = 'default'

const y = null ?? 'default'; // y = 'default'

const z = 'value' ?? 'default'; // z = 'value'

const a = '' ?? 'default'; // a = ''

const b = '' || 'default'; // b = 'default'

It should be noted that ??operators need to be used in ES11 and above versions.

3. Arrow Function

Functions can be defined more concisely using arrows (=>). For example:

const add = (a, b) => a + b;
console.log(add(1, 2)); // 3

const obj = {
  x: 1,
  add(y) {
    return this.x + y;
  },
  double: () => this.x * 2,
};
console.log(obj.add(2)); // 3
console.log(obj.double()); // NaN

Note that this in the arrow function points to the context at the time of definition, not the context at the time of calling.

4. Template Literals

Use backticks (`) to define strings that contain variables, expressions, and newlines. For example:

const name = "Alice";
const age = 20;
console.log(`My name is ${name}, and I am ${age} years old.`);
// 'My name is Alice, and I am 20 years old.'

5. Spread Operator

Use three dots (...) to expand an array or object into a list or multiple arguments. For example:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]

const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); // { x: 1, y: 2, z: 3 }

6. Short-circuit Evaluation

Use logical operators &&and ||short-circuit evaluation to simplify the writing of conditional branches . For example:

const obj = { prop: "value" };
const propValue = obj.prop || "default";
console.log(propValue); // 'value'

const arr = [];
const firstValue = arr[0] && arr[0].prop;
console.log(firstValue); // undefined

7. Shorthand conditional statement (Conditional (Ternary) Operator)

Using question marks and colons (?:) simplifies writing if-else statements. For example:

const age = 20;
const message = age >= 18 ? "You are an adult" : "You are not an adult";
console.log(message); // 'You are an adult'

8. Shorthand self-increment and self-decrement operators (Short-circuit Evaluation)

Incrementing and decrementing variables is simplified by using double plus signs (++) and double minus signs (--). For example:

let count = 0;
count++;
console.log(count); // 1

let num = 5;
const result = --num;
console.log(result); // 4

9. Shorthand assignment operator (Assignment Operator)

Compound assignment operations can be simplified by using plus and equal signs (+=), minus and equal signs (-=), multiplication and equal signs (*=), division and equal signs (/=), etc. For example:

let count = 0;
count += 1;
console.log(count); // 1

let num = 5;
num *= 2;
console.log(num); // 10

10. Double NOT Operator

The double negation operator (Double NOT Operator) is two consecutive exclamation marks ("!!"), also known as the logical NOT operator. It can convert a value to its corresponding Boolean value. For example:

const x = "hello";
console.log(!!x); // true

const y = 0;
console.log(!!y); // false

It should be noted that !!when using operators to convert Boolean values, care should be taken to avoid side effects caused by implicit type conversions , so as not to cause unexpected behavior.

11. ?:Represent optional properties in TypeScript

In TypeScript, you can use ?to indicate a property is optional. For example:

interface Person {
  name: string;
  age?: number;
}

const person1: Person = { name: "Alice" };
const person2: Person = { name: "Bob", age: 20 };

 In the above example, the Person interface has an optional property age, which means that it is possible to create an object of type Person where the age property is optional.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130497128