Sub topic 1
Objects and Property Lookup
Before you can understand prototypes, you need a precise picture of what happens when you write obj.key. This chapter covers what an object is, how property keys work, and the steps JavaScript takes to look up a property. Later chapters extend this lookup to the prototype chain, so the details here matter.
Prerequisites
This chapter assumes you already know:
- JavaScript object literals and how to read and write properties with dot and bracket notation
- How
thisis bound when you call a function as a method (obj.method()) - ES2015 syntax:
let,const, arrow functions, and template literals - How to run JavaScript in a browser console or with Node.js
Objects Are Collections of Properties
A JavaScript object is a collection of properties. Each property has a key and either a value or a pair of accessor functions. Every key is either a string or a Symbol. When you use any other type as a key, JavaScript converts it to a string first.
const user = {
name: 'Ada',
'favorite color': 'green',
42: 'answer'
};
console.log(user.name); // 'Ada'
console.log(user['favorite color']); // 'green'
console.log(user[42]); // 'answer'
console.log(user['42']); // 'answer' (same key)
console.log(Object.keys(user)); // ['42', 'name', 'favorite color']The number 42 became the string '42'. Object.keys also shows the order rule for string keys. Integer-like keys come first in ascending order, and the remaining string keys follow in insertion order.
Dot Notation versus Bracket Notation
| Form | Key source | Allowed keys | Typical use |
|---|---|---|---|
| `obj.key` | Literal identifier in the source code | Valid identifiers only | Fixed, known property names |
| `obj[expr]` | Result of evaluating `expr`, converted to a string or Symbol | Any string or Symbol | Dynamic names, names with spaces, Symbols |
A common mistake is to write obj.key when key is a variable. That form reads the property literally named "key". To use the variable's value as the key, write obj[key].
Key Conversion Gotchas
Because non-Symbol keys become strings, using objects as keys gives surprising results:
const cache = {};
const a = { id: 1 };
const b = { id: 2 };
cache[a] = 'first';
cache[b] = 'second';
console.log(Object.keys(cache)); // ['[object Object]']
console.log(cache[a]); // 'second'Both a and b convert to the string '[object Object]', so they refer to the same property. If you need object keys, use a Map.
Symbols are the other kind of key. They never collide with string keys, and Object.keys skips them:
const id = Symbol('id');
const record = { name: 'Ada' };
record[id] = 123;
console.log(record[id]); // 123
console.log(Object.keys(record)); // ['name']
console.log(Object.getOwnPropertySymbols(record)); // [Symbol(id)]Missing Properties versus Properties Set to undefined
Reading a property that does not exist returns undefined and does not throw an error. That makes a missing property look the same as a property whose value is undefined:
const settings = { theme: undefined };
console.log(settings.theme); // undefined
console.log(settings.font); // undefined
console.log('theme' in settings); // true
console.log('font' in settings); // false
console.log(Object.hasOwn(settings, 'theme')); // trueTo check whether a property exists, use in or Object.hasOwn. Don't compare the value with undefined. The two checks differ once prototypes are involved, and the chapter on own versus inherited properties covers the difference.
Properties Have Attributes
Each property carries hidden attributes besides its value. A data property has value, writable, enumerable, and configurable. You can inspect them with Object.getOwnPropertyDescriptor:
'use strict';
const point = { x: 1 };
console.log(Object.getOwnPropertyDescriptor(point, 'x'));
// { value: 1, writable: true, enumerable: true, configurable: true }
Object.defineProperty(point, 'y', { value: 2 });
console.log(Object.getOwnPropertyDescriptor(point, 'y'));
// { value: 2, writable: false, enumerable: false, configurable: false }
console.log(Object.keys(point)); // ['x'] (y is not enumerable)
try {
point.y = 10;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(point.y); // 2Properties created by assignment or by object literals default to true for all three flags. Properties created with defineProperty default to false. In sloppy mode, writing to a non-writable property fails silently. In strict mode, which includes ES modules and class bodies, it throws a TypeError.
Accessor Properties
An accessor property has a get function, a set function, or both, in place of a value. Reading the property calls the getter. Assigning to it calls the setter. Both run with this set to the object you accessed the property through.
const temperature = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(f) {
this.celsius = (f - 32) * 5 / 9;
}
};
console.log(temperature.fahrenheit); // 68
temperature.fahrenheit = 212;
console.log(temperature.celsius); // 100The rule that this refers to the object you accessed the property through, and not necessarily the object that holds the property, comes back when methods and accessors are inherited.
The Lookup Algorithm, Part One
When you evaluate obj.key or obj[key], the engine runs an internal operation called [[Get]]. Simplified:
- Convert the key to a string or Symbol.
- Check whether
objhas an own property with that key. - If it does and the property is a data property, return its value.
- If it does and the property is an accessor, call its getter with
thisset to the original object, and return the result. If there is no getter, returnundefined. - If it does not, continue the search somewhere else.
Step 5 is where this chapter stops. Here is evidence that the search does continue:
const empty = {};
console.log(Object.keys(empty)); // []
console.log(Object.hasOwn(empty, 'toString')); // false
console.log(typeof empty.toString); // 'function'
console.log(empty.toString()); // '[object Object]'empty has no own properties, but empty.toString is still a function. The lookup found it on a different object. The next chapter names that object and the hidden link that leads to it.
Exercise
Predict the output of each console.log: const k = { a: 1 }; const obj = { 1: 'one', b: undefined }; obj[k] = 'obj-key'; console.log(obj['1']); console.log('b' in obj, obj.c === obj.b); console.log(obj['[object Object]']); console.log(Object.keys(obj));
Show answer
'one' (the numeric key 1 is the string '1'); true true ('b' exists with value undefined, and the missing 'c' also reads as undefined); 'obj-key' (k converts to '[object Object]'); ['1', 'b', '[object Object]'] (integer-like key first, then the other string keys in insertion order).
Exercise
In strict mode, you run Object.defineProperty(o, 'id', { value: 7 }) and then o.id = 8. What happens, and what do Object.keys(o) and o.id return afterward, assuming o started as {}?
Show answer
The assignment throws a TypeError because writable defaults to false. Object.keys(o) returns [] because enumerable also defaults to false. o.id is still 7.