This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
preface
Optional chain? . Is a secure way to access object properties without error, even if a property does not exist in a nested object.
Problem accessing nested objects
When we write programs, there will always be an object property that may be null or non-existent, and when we directly access it, an error will be reported, as shown in the following code
let obj ={
username:"Flower".data: {age:18.height:170.weight:90,}}// Normal output, no problem
console.log("First output:"+obj.data.height)
// Obj. data = null
obj.data = null
console.log("Second output:"+obj.data.height)
Copy the code
This problem occurs when data does not exist, when data is Null, or when data is undefined.
Solution – Conditional judgment
The easiest way to solve these problems is to prevent errors through conditional judgment. As shown below.
obj ={
username:"Flower".data:null
}
if(obj.data){
console.log("Normal output:"+obj.data.height)
}else{
console.log("No data output")}Copy the code
However, the code becomes cumbersome and unreadable when there are too many levels, as shown below
obj ={
username:"Flower".data: {age:18.height:170.weight:90.unit: {weight:"kg".height:"cm".data: {a:"Deepest level parameter 1".b:"Deepest level parameter 2"}}}}// Check the normal output
if(obj.data && obj.data.unit && obj.data.unit.data ){
console.log(obj.data.unit.data.a)
}
Copy the code
The more levels of nesting, the more perverted the judgment becomes, so let’s talk about the use of optional chains.
Solution – Optional chain
We talked about optional chains, right? . Is a secure way to access object properties without error, even if a property does not exist in a nested object. If optional chain? . If the preceding part is undefined or null or an empty string, it stops and returns undefined.
In plain English: to access nested object properties normally, simply add an optional chain to the potentially empty property. . Then it will not continue to value and return the empty value of the attribute, we use several cases to verify
obj ={
username:"Flower".data: null.// data:{
// age:18,
// }
}
// Verify that data is null
console.log("Output:"+ obj.data? .age)Copy the code
The readability of the optional chain comes into play when the hierarchy is very deep
obj ={
username:"Flower".data: {age:18.height:170.weight:90.unit: {weight:"kg".height:"cm".data: {a:"Deepest level parameter 1".b:"Deepest level parameter 2"}}}}/ / optional link chain
console.log("Optional chain:"+ obj.data? .unit? .data? .a)// Normal output
console.log("Conditional judgment :"+obj.data.unit.data.a)
Copy the code
When an error occurs, such as obj.data = null, the following output appears
obj.data = null
/ / optional link chain
console.log("Optional chain:"+ obj.data? .unit? .data? .a)// Normal output
console.log("Conditional judgment :"+obj.data.unit.data.a)
Copy the code
You can safely delete values in addition to values, as shown in the following code
// obj = {
// name:123
// }
obj = null
console.log( deleteobj? .name )console.log( delete obj.name )
Copy the code
Matters needing attention
We know the alternative chain
? .
The preceding value takes effect as an optional value, but it must be a declared value, otherwise an error is reported
Optional chain extension? . ()? [].
Optional chains are a special type of operator that can also be used with functions and square brackets
With functions:
var obj = {
test(){
return "Test function called"}}// Used with functions, the function is called if it exists, and undefined is returned if it does not exist
console.log( obj.test?.() )
console.log( obj.test2?.() )
Copy the code
Used with square brackets:
var obj = {
data: {username: "Flower"}}var item1 = 'username'
var item2 = 'name'
console.log( obj.data? .[item1] )console.log( obj.data? .[item2] )Copy the code
conclusion
Optional chain? There are three syntax options for checking whether the left part of the string is null/undefined/ empty, and continuing if not. This gives us more secure access to nested object properties.
grammar | instructions |
---|---|
obj? .prop |
Returns if obj existsobj.prop Is returned otherwiseundefined |
obj? .[prop] |
Returns if obj existsobj[prop] Is returned otherwiseundefined |
obj.method? . () |
Called if obj existsobj.method Method, otherwise returnsundefined |