Its called "optional chaining" operator. It moves from left to right. if it sees ?. it checks the left value if its undefined or null. if yes, it returns undefined and stops moving to the right. that means if b is already undefined it wont check the values on the right side
Videos
Hi everyone!
I love optional chaining, i really do, but there are some cases where using this syntax damages the readability of the code. One of those cases is the following
function optionalFunction(){
console.log("works");
}
// optionalFunction = undefined;
optionalFunction?.(); While i understand this approach, i find it optionalFunction?.() harder to read as opposed to this
function optionalFunction(){
console.log("works");
}
// optionalFunction = undefined;
if(optionalFunction != undefined){
optionalFunction();
} I think i'd rather have a more readable and stronger check than ES6 magic when checking if an optional function is defined.
I believe that optional chaining fixes the problem of checking if a property of an object exists, and if exists, then get the value or keep going deeper in the object structure. But this syntax just looks weird for calling functions, it looks a lot like those "one line cleverness" code that sometimes people encounter.
What are your thoughts about this?
Its called "optional chaining" operator. It moves from left to right. if it sees ?. it checks the left value if its undefined or null. if yes, it returns undefined and stops moving to the right. that means if b is already undefined it wont check the values on the right side
In the example below, obj has only one key a.
const obj = {a: 1};
console.log(obj?.b);
In the above code snippet, there is no property b in object because of which it is printing undefined.
console.log(obj.b.c.d?.e);
console.log(obj.b?.c.d?.e);
Even in the code above, the same thing is happening where the object is not having key b hence it is printing undefined. So if you want to see that obj.b.c is undefined then the object should look the one below:
obj: {
b: '123'
}