The use of several special operators in JavaScript

Note: JavaScriptNull, undefined, false "", NaNWill be judged false

  • ||and??The difference between

| | and???? Mainly used to assign default values

/ / | | operators
const vaule = a || b; // If the value is null, undefined, "", false, NaN, the value on the right will take effect

/ /?? The operator
const value = a ?? b; // The value on the right takes effect only when the value on the left is null or undefined
Copy the code
  • &&The operator

The && operator is generally used for short-circuit detection and can also be used to assign default values

a && b; // Statement B is executed if and only if a is true

const value = a && b; // B will be assigned to value if and only if a is true, otherwise A will be assigned to value
Copy the code
  • !!!!!The operator

!!!!! Operators can quickly convert a value to its corresponding judgment value and can be used in data traversal functions that need to return a Boolean value (filter some find findIndex, etc.)

const a = null;
console.log(!! a);/ / output is false
Copy the code