What does accessing a non-existent property return?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Objects #JS Basics

Brief Answer

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.


Full Answer

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.

What JavaScript Returns

When accessing a non-existent property, undefined is always returned:

const user = { name: 'John' };
console.log(user.age); // undefined

Why undefined

JavaScript doesn’t throw an error because:

  1. Objects can be dynamic
  2. Properties can be added and removed
  3. This makes working with objects more flexible

Simple Examples

Regular Object

const obj = { a: 1 };
console.log(obj.b); // undefined
console.log(obj.c); // undefined

Nested Objects

const user = { 
  name: 'John',
  address: { city: 'Moscow' }
};
 
console.log(user.phone); // undefined
console.log(user.address.street); // undefined

Important Features

1. No Error

const obj = { a: 1 };
 
// Doesn't cause error
console.log(obj.nonExistent); // undefined
 
// Will cause error
console.log(obj.nonExistent.property); // TypeError!

2. undefined as Value

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!

When This is Useful

Existence Check

const user = { name: 'John' };
 
// Simple check
if (user.age === undefined) {
  console.log('Age not specified');
}

Working with Optional Data

const config = { theme: 'dark' };
// No need to check each parameter
const lang = config.language || 'en'; // 'en' by default

Common Mistakes

1. Expecting Error

// ❌ Thinking there will be error
const obj = { a: 1 };
console.log(obj.b); // undefined, not error!
 
// ✅ Proper understanding
console.log(obj.b === undefined); // true

2. Chain of Non-existent Properties

// ❌ 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); // undefined

Simple Rules

  1. undefined — always returned when accessing non-existent property
  2. No error — JavaScript doesn’t throw error in this case
  3. Careful with chains — obj.a.b causes error if obj.a doesn’t exist
  4. Check — can be used to check property existence
  5. Flexibility — this makes working with objects more flexible

Understanding 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 💪