Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Strange syntax, what does `?.` mean in JavaScript?
The ?. operator is called optional chaining and provides a safe way to access nested object properties without throwing errors when intermediate properties are undefined or null.
The Problem with Regular Property Access
Consider this nested object describing a person:
const being = {
human: {
male: {
age: 23
}
}
};
console.log(being.human.male.age);
23
This works fine, but what happens if we try to access a property that doesn't exist?
const being = {
human: {
male: {
age: 23
}
}
};
// This will throw an error
try {
console.log(being.human.female.age);
} catch (error) {
console.log("Error:", error.message);
}
Error: Cannot read properties of undefined (reading 'age')
Solution: Optional Chaining (?.)
Optional chaining allows safe property access. If any part of the chain is undefined or null, it stops and returns undefined instead of throwing an error:
const being = {
human: {
male: {
age: 23
}
}
};
// Safe access - returns undefined instead of error
console.log(being?.human?.female?.age);
console.log(being?.human?.male?.age);
undefined 23
Common Use Cases
Optional chaining works with arrays, function calls, and computed properties:
const user = {
profile: {
contacts: ["email@example.com"],
getName: function() { return "John"; }
}
};
// Array access
console.log(user?.profile?.contacts?.[0]);
// Function call
console.log(user?.profile?.getName?.());
// Non-existent path
console.log(user?.settings?.theme?.color);
email@example.com John undefined
Comparison
| Method | Safe Access? | Returns on Missing Property |
|---|---|---|
obj.prop.nested |
No | Throws TypeError |
obj?.prop?.nested |
Yes | Returns undefined |
Conclusion
Optional chaining (?.) prevents errors when accessing nested properties that might not exist. Use it when dealing with uncertain object structures or API responses.
