Hackforge Academy

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');

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community