Category: javascript
how to handle undefined object in javascript
Published on 18 May 2026
Explanation
Optional chaining (?.) safely accesses
object properties without throwing an error
if the object is undefined or null.
Code:
let user = undefined; console.log(user?.name);
Explanation
Optional chaining can also be used
for nested objects to avoid 'Cannot
read properties of undefined' errors.
Code:
let data = {};
console.log(data.user?.profile?.email);
Explanation
You can manually check whether an
object is undefined before accessing its
properties.
Code:
if(user !== undefined){
console.log(user.name);
}
Explanation
Using a simple truthy check is
a shorter way to verify the
object exists.
Code:
if(user){
console.log(user.name);
}
Explanation
The nullish coalescing operator (??)
provides a default value when the result
is undefined or null.
Code:
let username = user?.name ?? 'Guest'; console.log(username);
Explanation
Default function parameters help avoid
errors when an object argument is not
passed.
Code:
function printUser(user = {}){
console.log(user.name);
}
printUser();
Explanation
Try-catch can handle runtime errors caused
by accessing properties of undefined objects.
Code:
try{
console.log(user.name);
}catch(err){
console.log('User object is undefined');
}
Explanation
A common modern pattern combines optional
chaining and nullish coalescing for safe
access with default values.
Code:
console.log(user?.name ?? 'Unknown');