The optional chain operator (? .) allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid. ? The. Operator functions like the. Chain operator, except that it does not raise an error if the reference is null (or undefined), and the expression shorts out the return value of undefined. When used with a function call, returns undefined if the given function does not exist.
The optional chain operator makes the expression shorter and more concise when trying to access an object property that may not exist.
A, grammar,
obj? .prop; obj? .[expr]; arr? .[index]; func? .(args);Copy the code
Well, let’s start with a simple use:
Const obj = {name: 'baz ', 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.comCopy the code
The operator implicitly checks whether an object’s property is null or undefined, making the code more elegant and concise.
const name = obj? .name; const name1 = obj === null || obj === undefined ? undefined : obj.name; / / is equivalent toCopy the code
Two, use scenarios
2.1 Combined with function calls
Const result = obj? Const result = obj? .method? . ();Copy the code
2.2 Handling optional callback functions
function invoke(fn) { if (fn) { fn.call(this); Function betterInvoke(fn) {fn? .call(this); }Copy the code
2.3 Optional chains and expressions
const obj = { propName: 'name' }; console.log(obj? .['prop' + 'Name']); // nameCopy the code
2.4 Optional chains cannot be used for assignment
const obj = { propName: 'name' }; obj? .['propName'] = 'new name'; // Syntax ErrorCopy the code
2.5 Accessing an array element
const first = arr? . [0];Copy the code
2.6 Short-circuit Characteristics
If the left side of the optional chain is NULL or undefined, subsequent operations will not be performed.
const name = a? .b? .c? .d;Copy the code
In real development, however, we need a default value, so we can use the double question mark?? Operators.
const name = a? .b? .c? .d?? 'shanguagua';Copy the code