When accessing a non-existent object property, JavaScript returns undefined. This happens because JavaScript first looks for the property in the object, and if not found, returns undefined instead of throwing an error.
When you try to get the value of a property that doesn’t exist in an object, JavaScript behaves in a special way. It’s important to understand this for proper work with objects.
When accessing a non-existent property, undefined is always returned:
const user = { name: 'John' };
console.log(user.age); // undefinedJavaScript doesn’t throw an error because:
const obj = { a: 1 };
console.log(obj.b); // undefined
console.log(obj.c); // undefinedconst user = {
name: 'John',
address: { city: 'Moscow' }
};
console.log(user.phone); // undefined
console.log(user.address.street); // undefinedconst obj = { a: 1 };
// Doesn't cause error
console.log(obj.nonExistent); // undefined
// Will cause error
console.log(obj.nonExistent.property); // TypeError!const obj = {
value: undefined,
missing: undefined // Actually property doesn't exist
};
console.log(obj.value); // undefined
console.log(obj.missing); // undefined
// But these are different situations!const user = { name: 'John' };
// Simple check
if (user.age === undefined) {
console.log('Age not specified');
}const config = { theme: 'dark' };
// No need to check each parameter
const lang = config.language || 'en'; // 'en' by default// ❌ Thinking there will be error
const obj = { a: 1 };
console.log(obj.b); // undefined, not error!
// ✅ Proper understanding
console.log(obj.b === undefined); // true// ❌ Error — can't read properties of undefined
const obj = { a: 1 };
console.log(obj.b.c); // TypeError!
// ✅ Safe way
console.log(obj.b && obj.b.c); // undefinedUnderstanding this behavior helps write more reliable code and avoid unexpected errors.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪