Suppose we have this object:
let obj = {};
What exactly each of these expressions do?
obj.a?.().b
obj.a()?.b
obj.a?.()?.b
obj.a?.().b
Dereference obj
directly.
Dereference obj.a
in a null-safe way - it will stop at this point if the property is not there, it is undefined
or null
. If that happens the result of evaluating the expression will be undefined
.
Execute that value directly.
Receive the return result and continue.
Get the property b
from the result directly.
const tryIt = obj => {
console.log("------start------");
console.log("trying with", obj );
try {
console.log( "result", obj.a?.().b );
} catch (e) {
console.error("problem", e.message);
}
console.log("-------end-------");
}
tryIt( null ); // ERROR
tryIt( {} ); // undefined
tryIt( { a: undefined } ); // undefined
tryIt( { a: null } ); // undefined
tryIt( { a: false } ); // ERROR
tryIt( { a: "hello" } ); // ERROR
tryIt( { a: function() {} } ); // ERROR
tryIt( { // ERROR
a: function() {
return null;
}
});
tryIt( { // 42
a: function() {
return { b: 42 };
}
});
obj.a()?.b
Dereference obj
directly.
Dereference obj.a
directly.
Executing that value directly.
Handle the value in a null-safe way - it will stop at this point if the return value is null
or undefined
. If that happens the result of evaluating the expression will be undefined
.
Get the property b
from the result directly.
const tryIt = obj => {
console.log("------start------");
console.log("trying with", obj );
try {
console.log( "result", obj.a()?.b );
} catch (e) {
console.error("problem", e.message);
}
console.log("-------end-------");
}
tryIt( null ); // ERROR
tryIt( {} ); // ERROR
tryIt( { a: undefined } ); // ERROR
tryIt( { a: null } ); // ERROR
tryIt( { a: false } ); // ERROR
tryIt( { a: "hello" } ); // ERROR
tryIt( { a: function() {} } ); // undefined
tryIt( { // undefined
a: function() {
return null;
}
});
tryIt( { // 42
a: function() {
return { b: 42 };
}
});
obj.a?.()?.b
Dereference obj
directly.
Dereference obj.a
in a null-safe way - it will stop at this point if the property is not there, it is undefined
or null
. If that happens the result of evaluating the expression will be undefined
.
Executing that value directly.
Handle the value in a null-safe way - it will stop at this point if the return value is null
or undefined
. If that happens the result of evaluating the expression will be undefined
.
Get the property b
from the result directly.
const tryIt = obj => {
console.log("------start------");
console.log("trying with", obj );
try {
console.log( "result", obj.a?.()?.b );
} catch (e) {
console.error("problem", e.message);
}
console.log("-------end-------");
}
tryIt( null ); // ERROR
tryIt( {} ); // undefined
tryIt( { a: undefined } ); // undefined
tryIt( { a: null } ); // undefined
tryIt( { a: false } ); // ERROR
tryIt( { a: "hello" } ); // ERROR
tryIt( { a: function() {} } ); // undefined
tryIt( { // undefined
a: function() {
return null;
}
});
tryIt( { // 42
a: function() {
return { b: 42 };
}
});