Optional Chaining Operator Flashcards
What does the optional chaining operator do when accessing an object s property?
Checks if the object is undefined or null, it returns undefined instead of throwing an error.
If the variable myObject has not been declared will the following throw an error.
myObject?.name
Yes it will throw the following error:
Uncaught ReferenceError: myObject is not defined
This is because the optional chaining operator returns undefined instead of throwing an error if the object is undefined or null. In this case the object doesn’t even exist as it hasn’t been declared.
What is a nullish value? Are nullish values falsy?
In JavaScript, a nullish value is a value which is either null or undefined. Nullish values are always falsy.
Will this throw an error?
let myObject;
myObject.name
Yes because myObject is undefined.
Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)
Will this throw an error?
let myObject;
myObject?.name
No the optional chaining operator checks if myObject is nullish and because it is it is doesn’t try and access the “name” property.
It will return undefined.