Skip to main content

Nonexistent object property

Short answer

If you access a nonexistent property of an object, no error occurs, and the result is undefined.


Example

javascript
const user = { name: 'Oleh' }; console.log(user.name); // "Oleh" console.log(user.age); // undefined console.log(user.address); // undefined

JavaScript does not throw an error, it just returns undefined.


Why this happens

When JS accesses a property, it:

  1. Checks whether it exists on the object.
  2. If it exists → returns its value.
  3. If it does not → returns undefined.

That is:

javascript
user.hasOwnProperty('age'); // false user.age; // undefined

But important: an error appears if you go further down the chain

javascript
console.log(user.address.city); // TypeError

Why? user.address is undefined, and you cannot request properties (city) on undefined.


How to avoid the error when accessing nested properties

Method 1. Manual checks

javascript
if (user.address && user.address.city) { console.log(user.address.city); }

Method 2. The optional chaining operator ?. (the modern approach)

javascript
console.log(user.address?.city); // undefined (but no error!)

If the left side of ?. is null or undefined, JS stops evaluation and returns undefined.


Method 3. Use a default value via ??

javascript
console.log(user.address?.city ?? 'Not specified'); // "Not specified"

Example with a dynamic key

javascript
const key = 'email'; console.log(user[key]); // undefined (if the property does not exist)

Even with dynamic access via [] the behavior is the same, just undefined.


Difference from other cases

SituationResultExplanation
user.ageundefinedThe property is missing
user.age.cityTypeErrorundefined is not an object
'age' in userfalseChecks whether the property exists
user.hasOwnProperty('age')falseChecks only own properties
user.name ?? 'no''Oleh'Returns the value
user.age ?? 'no''no'Default value

Summary

BehaviorWhat it does
obj.missingreturns undefined
No erroreven if the property is missing
An error appearswhen trying to go deeper (undefined.city)
Solutionuse ?. or ??

Example to reinforce this

javascript
const user = { name: 'Oleh' }; console.log(user.age); // undefined console.log(user.age?.value); // undefined (no error) console.log(user.age.value); // TypeError console.log(user.age ?? 'no'); // "no"

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.