Optional Chaining Operator Flashcards

1
Q

What does the optional chaining operator do when accessing an object s property?

A

Checks if the object is undefined or null, it returns undefined instead of throwing an error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

If the variable myObject has not been declared will the following throw an error.

myObject?.name

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a nullish value? Are nullish values falsy?

A

In JavaScript, a nullish value is a value which is either null or undefined. Nullish values are always falsy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Will this throw an error?

let myObject;
myObject.name

A

Yes because myObject is undefined.

Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Will this throw an error?

let myObject;
myObject?.name

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly