Skip to main content

Optional Chaining Operator

Objects the Basics: Optional Chaining



What is the optional chaining operator in JavaScript?

View Answer:
Interview Response: The optional chaining operator is a safe way to access nested object properties, even if an intermediate property does not exist.

Can you explain what JavaScript's optional chaining operator (?.) does?

View Answer:
Interview Response: JavaScript's optional chaining operator (?.) allows you to access nested properties of an object while protecting against null or undefined values, by short-circuiting the evaluation if a property is missing.

Code Example:

let user = {}; // user has no address

console.log(user?.address?.street); // undefined (no error)

let user2 = {};
console.log(user2.address.street); // returns a type error

What will the optional chaining operator (?.) return if an object does not exist?

View Answer:
Interview Response: The optional chaining operator returns undefined if the object does not exist (equals null). We will see this outcome when an object gets set to null. If the object is not defined, it results in a reference error.

Code Example:

let user = null;

console.log(user?.address); // undefined
console.log(user?.address.street); // undefined

console.log(myUser?.address.street); // returns a reference error

When should the optional chaining (?.) operator be used?

View Answer:
Interview Response: We should use the option chaining operator with the intent to handle object properties that are already known to be optional.

Code Example: Short Circuit results in a false response.

let user = null;
let x = 0;

user?.sayHi(x++); // no "sayHi", so the execution doesn't reach x++

console.log(x); // 0, value not incremented.

note

If it is not optional, it can result in a false scenario that goes unchecked. This behavior could result in silent coding errors and become more challenging to debug.


Is optional chaining (?.) merely an operator or a syntax construct?

View Answer:
Interview Response: Technically, it is a syntax construct, but most developers refer to it as an operator.

Technical Response: It is technically a syntactic construct. However, it generally gets referred to as an operator. It is more than simply an operator, though, and may get used with functions (?.()) and square brackets (?.[]). For instance, ?.() is used to invoke a function that may or may not exist. If we want to utilize brackets [] instead of dot to access properties, we may use the?.[] syntax (.).

Code Example: Function Call

let userAdmin = {
admin() {
console.log('I am admin');
},
};

let userGuest = {};

userAdmin.admin?.(); // I am admin

userGuest.admin?.(); // nothing (no such method)

Code Example: Bracket Property Check

let key = 'firstName';

let user1 = {
firstName: 'John',
};

let user2 = null;

console.log(user1?.[key]); // John
console.log(user2?.[key]); // undefined

Can you use the optional chaining operator to write or store values?

View Answer:
Interview Response: You can use the optional chaining operator (?.) for safe reading and deleting, but not writing. The optional chaining operator (?.) has no use on the left side of an assignment.

Code Example:

let user = null;

user?.name = "John"; // Error, does not work
// because it evaluates to undefined = "John"

How does optional chaining differ from traditional object property access?

View Answer:
Interview Response: Optional chaining in JavaScript allows safe access to deeply nested properties of an object without having to check each intermediate object in the chain for null or undefined, reducing error risk.

Traditional object property access:

let name = obj && obj.user && obj.user.name ? obj.user.name : 'default';

Using optional chaining:

let name = obj?.user?.name ?? 'default';

What are some potential pitfalls of using the optional chaining operator?

View Answer:
Interview Response: Overuse of optional chaining can decrease code readability and obscure real errors by skipping necessary null or undefined checks. It may not be supported in older browsers.

Code Example:

// A hypothetical object with nested structure
let user = {
profile: {
name: "Alice",
address: {
street: "10 Downing St."
// city is missing
}
}
}

// Using optional chaining
let city = user?.profile?.address?.city; // undefined

// Now, if you're expecting city to be a String, this could lead to unintended behavior
console.log(city.toUpperCase()); // TypeError: Cannot read properties of undefined (reading 'toUpperCase')


Is the optional chaining operator widely supported in modern browsers?

View Answer:
Interview Response: Yes, the optional chaining operator is widely supported in modern browsers, including all major desktop and mobile browsers as well as Node.js.

How does the optional chaining operator differ from the nullish coalescing operator (??)?

View Answer:
Interview Response: The optional chaining operator (?.) safely accesses nested object properties, while the nullish coalescing operator (??) provides a default value for null or undefined values.

Code Example:

// Optional chaining operator (?.)
let obj = {
data: {
name: "Alice"
}
};

let name1 = obj?.data?.name; // "Alice"
let age1 = obj?.data?.age; // undefined

// Nullish coalescing operator (??)
let name2 = obj?.data?.name ?? "Unknown"; // "Alice"
let age2 = obj?.data?.age ?? 25; // 25