Sub topic 1
What Happens When You Touch an Object: Internal Methods
Every time your code reads a property, assigns one, checks in, or calls a function, the JavaScript engine turns that syntax into a call to a small, fixed set of operations. The specification calls these operations internal methods. You can't call them by name. They are written in double square brackets, such as [[Get]] and [[Set]], and they are the vocabulary a Proxy works in. If you know which internal method a piece of syntax triggers, you can predict exactly what a proxy can intercept and what it can't.
This chapter covers that vocabulary before any proxy appears. The rest of the tutorial builds on it.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript objects, properties, and property descriptors (
value,writable,enumerable,configurable,get,set) - Prototypes and how property lookup walks the prototype chain
- Functions,
thisbinding, and constructors called withnew - ES6 syntax: arrow functions, classes, template literals, destructuring
- Symbols at a basic level
All code runs in Node.js 16+ or any modern browser console. Examples that depend on strict mode say so.
The Essential Internal Methods
The specification says every object supports eleven essential internal methods. Function objects add two more. The table below lists them with the syntax that typically triggers each one. In later chapters every row gets a matching proxy trap.
| Internal method | Triggered by (examples) | Returns |
|---|---|---|
| `[[Get]]` | `obj.x`, `obj[key]`, destructuring | the value |
| `[[Set]]` | `obj.x = v`, `obj[key] = v` | boolean success |
| `[[HasProperty]]` | `key in obj`, `with` lookups | boolean |
| `[[Delete]]` | `delete obj.x` | boolean success |
| `[[OwnPropertyKeys]]` | `Object.keys`, `Reflect.ownKeys`, `for...in`, spread `{...obj}` | list of keys |
| `[[GetOwnProperty]]` | `Object.getOwnPropertyDescriptor`, `Object.hasOwn`, and internally during `[[Get]]`/`[[Set]]` | descriptor or undefined |
| `[[DefineOwnProperty]]` | `Object.defineProperty`, and internally when assignment creates a property | boolean success |
| `[[GetPrototypeOf]]` | `Object.getPrototypeOf`, `instanceof`, `__proto__` getter | object or null |
| `[[SetPrototypeOf]]` | `Object.setPrototypeOf`, `__proto__` setter | boolean success |
| `[[IsExtensible]]` | `Object.isExtensible`, `Object.isFrozen` | boolean |
| `[[PreventExtensions]]` | `Object.preventExtensions`, `Object.freeze`, `Object.seal` | boolean success |
| `[[Call]]` (functions only) | `fn(...)`, `fn.call`, `fn.apply` | the return value |
| `[[Construct]]` (constructors only) | `new Fn(...)`, `super(...)` | an object |
Look at the "Returns" column. Most internal methods that change state report success with a boolean. They don't throw. The surrounding syntax decides what a false means, and that decision explains several behaviors that confuse intermediate developers. It comes up again below.
Ordinary and Exotic Objects
An ordinary object uses the default algorithm the specification defines for every internal method. Object literals, class instances, and objects from Object.create are ordinary.
An exotic object replaces at least one internal method with different behavior. You already use several:
- Arrays override
[[DefineOwnProperty]], so writing an index can growlengthand writinglengthcan delete elements. - String objects expose their characters as read-only indexed properties.
- Bound functions override
[[Call]]and[[Construct]]to add a fixedthisand preset arguments. - Module namespace objects refuse all writes.
- Proxies replace every internal method with a call to your handler.
const arr = [1, 2, 3];
arr.length = 1; // array's [[DefineOwnProperty]] removes elements
console.log(arr); // [ 1 ]
arr[5] = 'x'; // writing an index past the end grows length
console.log(arr.length); // 6A plain object with a length property does none of this. The difference lives entirely in the internal method. A proxy is the one exotic object whose internal methods you get to write yourself.
Walking Through [[Get]]
A property read does more than look up a key. The ordinary [[Get]](key, receiver) algorithm works like this:
- Call
[[GetOwnProperty]](key)on the current object. - If no own property exists, call
[[GetPrototypeOf]](). If the prototype isnull, returnundefined. If not, call the prototype's[[Get]](key, receiver)and pass along the same receiver. - If the property is a data property, return its
value. - If it is an accessor, call its getter with
thisset toreceiver. If there is no getter, returnundefined.
The receiver is the object the access started on. It stays fixed while the lookup climbs the chain, which is how an inherited getter ends up seeing the object you actually accessed:
const base = {
get description() {
return `I am ${this.name}`;
}
};
const cat = Object.create(base);
cat.name = 'Tom';
console.log(cat.description); // 'I am Tom'
// The getter lives on base, but this === cat (the receiver).Reflect.get calls [[Get]] directly and lets you choose the receiver. The next example is a preview. A later chapter explains why this argument matters so much for proxies.
const obj = {
name: 'obj',
get who() { return this.name; }
};
console.log(obj.who); // 'obj'
console.log(Reflect.get(obj, 'who', { name: 'other' })); // 'other'Walking Through [[Set]]
Assignment surprises people more than reads do. A common assumption is that obj.x = v always creates or updates an own property x on obj. The ordinary [[Set]](key, value, receiver) algorithm does something else:
- Look for an own property with
[[GetOwnProperty]]. If there isn't one, move up the prototype chain and run[[Set]]there with the same receiver. If the chain ends, act as if a writable data property was found. - If the property found is an accessor, call its setter with
this = receiver. If it has no setter, returnfalse. - If the property found is a non-writable data property, return
false. This applies even when the property is inherited. - If not, define or update an own data property on the receiver with
[[DefineOwnProperty]].
Two results follow directly. First, an inherited setter runs in place of creating an own property:
'use strict';
const base = {
set label(v) { this._label = v.toUpperCase(); }
};
const item = Object.create(base);
item.label = 'hi';
console.log(Object.hasOwn(item, 'label')); // false: no own 'label' was created
console.log(Object.hasOwn(item, '_label')); // true: the setter wrote to the receiver
console.log(item._label); // 'HI'Second, a non-writable property on the prototype blocks assignment on every object that inherits from it:
'use strict';
const proto = Object.defineProperty({}, 'id', { value: 1, writable: false });
const obj = Object.create(proto);
try {
obj.id = 2;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(obj.id); // 1, still inheritedBooleans, Strict Mode, and Thrown Errors
[[Set]], [[Delete]], [[DefineOwnProperty]], and the other mutating internal methods return false on failure. Different callers handle that false differently:
| Caller | On `false` |
|---|---|
| `obj.x = v` in strict mode | throws `TypeError` |
| `obj.x = v` in sloppy mode | fails silently |
| `delete obj.x` in strict mode | throws `TypeError` |
| `delete obj.x` in sloppy mode | evaluates to `false` |
| `Object.defineProperty` | always throws `TypeError` |
| `Reflect.defineProperty`, `Reflect.set`, `Reflect.deleteProperty` | return the boolean as-is |
const sealed = Object.seal({ x: 1 });
console.log(delete sealed.x); // false (sloppy mode script)
console.log(Reflect.deleteProperty(sealed, 'x')); // false
console.log(sealed.x); // 1This split matters later on. Proxy traps for these operations must return booleans, just like the internal methods they replace. The Reflect functions return those booleans unchanged, so they make the natural default inside a trap.
Key Enumeration and Its Order
[[OwnPropertyKeys]] returns every own key: strings and symbols, enumerable and not. Higher-level functions filter that list:
Reflect.ownKeys(obj)returns everything.Object.getOwnPropertyNames(obj)returns string keys only.Object.keys(obj)returns enumerable string keys. It checks each key with[[GetOwnProperty]].for...inalso walks the prototype chain, using[[GetPrototypeOf]].
For ordinary objects the order is fixed: integer-like keys in ascending numeric order, then string keys in the order they were created, then symbols in the order they were created.
const s = Symbol('s');
const o = { b: 1, 2: 'two', a: 2, [s]: 3, 1: 'one' };
console.log(Reflect.ownKeys(o)); // [ '1', '2', 'b', 'a', Symbol(s) ]
console.log(Object.keys(o)); // [ '1', '2', 'b', 'a' ]in Versus hasOwn
key in obj calls [[HasProperty]], which walks the prototype chain. Object.hasOwn(obj, key) calls [[GetOwnProperty]] on the object alone. Because they are different internal methods, a proxy can make them disagree, and a proxy that customizes one usually needs to customize the other too.
const parent = { inherited: true };
const child = Object.create(parent);
console.log('inherited' in child); // true ([[HasProperty]])
console.log(Object.hasOwn(child, 'inherited')); // false ([[GetOwnProperty]])[[Call]] and [[Construct]]
A value is callable only if it has [[Call]]. It works with new only if it also has [[Construct]]. Regular functions and classes have [[Construct]]. Arrow functions and methods defined with shorthand syntax don't. Classes are the reverse case: they have [[Call]], but it always throws.
const arrow = () => {};
class Point {}
try { new arrow(); } catch (e) { console.log(e.message); } // arrow is not a constructor
try { Point(); } catch (e) { console.log(e.message); } // Class constructor Point cannot be invoked without 'new'These two internal methods are why the apply and construct traps only work when the proxy's target is a function. A proxy has [[Call]] only if its target does.
Internal Methods Are Not Internal Slots
The specification also defines internal slots, such as [[MapData]] on a Map or [[DateValue]] on a Date. Slots hold hidden state. Internal methods are operations. A proxy can replace internal methods, but it has none of its target's slots. That gap causes some of the most common proxy failures, which the final chapter covers.
Common Mistakes
- Assuming assignment always creates an own property. Inherited setters and inherited non-writable properties change the result.
- Treating
inandhasOwnas the same check. They call different internal methods. - Expecting mutation failures to throw. Internal methods return
false, and whether that becomes an error depends on the caller and on strict mode. - Forgetting that one statement can call several internal methods.
Object.keys, spread, and assignment each call more than one.
Exercise
In strict mode, proto has a non-writable data property color with value 'red', and obj = Object.create(proto). What happens on obj.color = 'blue', and which internal method decides the outcome?
Show answer
It throws a TypeError, and obj.color stays 'red'. obj.[[Set]] finds no own property and defers to proto.[[Set]]. That step finds a non-writable data property and returns false. Strict-mode assignment turns false into a TypeError. Calling Object.defineProperty(obj, 'color', { value: 'blue' }) would succeed, because it calls [[DefineOwnProperty]] on obj directly and skips the prototype check.
Exercise
List the internal methods an ordinary object receives during Object.keys({ a: 1, b: 2 }), in order.
Show answer
[[OwnPropertyKeys]] once, which returns ['a', 'b']. Then [[GetOwnProperty]]('a') and [[GetOwnProperty]]('b'), to check that each key is enumerable. No [[Get]] call happens, because Object.keys never reads values.
Exercise
A getter get full() { return this.first + ' ' + this.last; } sits on a prototype. Why does Reflect.get(proto, 'full', { first: 'Ada', last: 'Lovelace' }) return 'Ada Lovelace'?
Show answer
[[Get]] finds the accessor on proto and calls its getter with this set to the receiver argument. Here the receiver is the passed object, not proto, so the getter reads first and last from it.