The role and use of the '??' operator and the '?.' operator in js

?? operator

In JavaScript, two question marks (??) are a new logical operator called the Nullish Coalescing operator, which is used to determine whether a variable is null or undefined, and if so, returns a default value. Its syntax is as follows:

Copy

variable ?? defaultValue

Among them, variable is the variable to be judged, and defaultValue is the default value.

For example, the following code uses the Nullish Coalescing operator to get the value of a variable and return a default value if the variable is null or undefined:

Copy

const foo = null;
const bar = 0;

console.log(foo ?? "default"); // "default"console.log(bar ?? "default"); // 0

In the above example, the first console.log returns the default value "default" because foo has a value of null, while the second console.log returns 0 because bar is not null or undefined.

?. operator

In JavaScript, the question mark period (?.) operator is an optional chain operator. Its function is to access the properties or methods of nested objects. If the object or property does not exist, no exception will be thrown. Instead it returns undefined. Its syntax is as follows:

Copy

object?.propertyobject?.method()

Among them, object is the object to be accessed, property is the attribute of the object, and method is the method of the object.

For example, the following code uses the question mark period operator to access properties and methods of nested objects, and returns undefined if the object or property does not exist:

Copy

const person={  name:"Alice",
  age:25,
  address:{    city:"Shanghai",
    district:"Pudong"}};

console.log(person.address?.city);// "Shanghai"
console.log(person.address?.street?.name);// undefined

In the above example, the first console.log returns "Shanghai", because the address object exists, and the city attribute also exists; while the second console.log returns undefined, because the address object exists, but the street attribute does not exist .

Guess you like

Origin blog.csdn.net/qq_45758925/article/details/129734662