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); // undefinedJavaScript does not throw an error, it just returns
undefined.
Why this happens
When JS accesses a property, it:
- Checks whether it exists on the object.
- If it exists → returns its value.
- If it does not → returns
undefined.
That is:
javascript
user.hasOwnProperty('age'); // false
user.age; // undefinedBut important: an error appears if you go further down the chain
javascript
console.log(user.address.city); // TypeErrorWhy?
user.addressisundefined, and you cannot request properties (city) onundefined.
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
?.isnullorundefined, JS stops evaluation and returnsundefined.
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, justundefined.
Difference from other cases
| Situation | Result | Explanation |
|---|---|---|
user.age | undefined | The property is missing |
user.age.city | TypeError | undefined is not an object |
'age' in user | false | Checks whether the property exists |
user.hasOwnProperty('age') | false | Checks only own properties |
user.name ?? 'no' | 'Oleh' | Returns the value |
user.age ?? 'no' | 'no' | Default value |
Summary
| Behavior | What it does |
|---|---|
obj.missing | returns undefined |
| No error | even if the property is missing |
| An error appears | when trying to go deeper (undefined.city) |
| Solution | use ?. 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.