JavaScript Optional Chaining — What Happens With Null?
This is a daily Javascript challenge from the CodeShot archive. Practice your knowledge of Optional Chaining Null Safe Access and improve your technical interview readiness.
const user = null
console.log(user?.name)
console.log(user?.address?.city)
Detailed Explanation
Why This Question Matters
We've all been there: you're debugging a production crash and you see the dreaded TypeError: Cannot read property 'x' of null. For years, the only way to avoid this was to write those nested "if" statements or long chains of && checks that made the code look like a staircase.
Optional chaining (?.) was introduced to solve this. It’s a lifesaver, but it's also a bit of a "magic" operator. If you don't understand exactly how it handles null or undefined, you might accidentally swallow bugs or write logic that doesn't behave the way you expect. This specific question tests whether you actually understand the mechanism or if you're just guessing that "it probably won't crash."
Understanding the Code
Let's look at the snippet:
At first glance, this looks like we're trying to access properties on something that doesn't exist. In standard JavaScript, user.name would throw an immediate error because you can't access a property of null.
Here is what's happening under the hood with the ?. operator:
When JavaScript hits the ?. operator, it performs a check. It asks: *"Is the value to the left of me null or undefined?"*
1. If the answer is yes, the engine stops evaluating that specific chain immediately. It doesn't even look at the property name (name or address). Instead, it simply returns undefined.
2. If the answer is no, it continues as a normal property access.
In the first line, user is null. The operator sees this, stops right there, and returns undefined.
In the second line, user?.address?.city, the same thing happens at the very first link in the chain. Because user is null, the engine doesn't even bother checking if address exists or if city is inside it. It short-circuits the entire expression and returns undefined.
Finding the Correct Answer
If you're looking at a multiple-choice question where the options are things like "Throws an error," "Returns null," or "Returns undefined," the correct answer is Option B: undefined.
Why not null? This is a common point of confusion. Even though the variable user is explicitly set to null, the optional chaining operator is designed to return undefined whenever the chain is broken. It doesn't "pass through" the null value; it replaces the result of the failed access with undefined.
Why not a TypeError? That's the whole point of the operator. The ?. syntax is essentially a shorthand for:
user === null || user === undefined ? undefined : user.name
Common Mistakes Developers Make
The most frequent mistake I see is using optional chaining when you actually *want* the code to fail.
If user being null represents a critical failure in your app (like a session that should definitely exist), using ?. will hide that bug. Your app won't crash, but you'll end up with undefined flowing through your logic, and you'll spend two hours wondering why your UI is blank instead of seeing a clear error in the console.
Another trip-up is thinking ?. works on everything. It only works for property access, element access (?.[]), and function calls (?.()). You can't use it to "optionally" perform a mathematical operation or a loop.
Also, remember that optional chaining is read-only. You cannot do this:
user?.name = 'John'; // SyntaxError
You can't assign a value to a chain that might not exist.
Real-World Usage
In a real production environment, you'll see this most often when dealing with API responses.
Imagine you're fetching a user profile from a REST API. Some users have a profile object, some don't. Some profiles have a socials object, and some of those socials have a twitter handle.
Without optional chaining, your code looks like this:
With optional chaining, it becomes:
Notice I used the Nullish Coalescing operator (??) at the end. This is the perfect partner for optional chaining. Since ?. returns undefined when a link is missing, ?? allows you to provide a sensible default value if the chain breaks.
Key Takeaways
- ?. checks for null or undefined before attempting to access a property.
- If the left side is nullish, the expression short-circuits and returns undefined.
- It does not matter how deep the chain is; if the first link is null, the whole thing results in undefined.
- Use it for optional data (like API responses), but avoid it for required data where a crash is actually a helpful signal that something is wrong.
- Pair it with ?? to handle default values gracefully.
Why this matters
Understanding Optional Chaining Null Safe Access is crucial for passing technical interviews. In real-world applications, this concept often leads to subtle bugs if not handled correctly. For more details, you can always refer to the official MDN Documentation.