completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Internal methods & exotic objects

Learn how ECMAScript object methods explain property reads and writes, arrays, arguments, typed arrays, modules, proxies, and their invariants.

By the end, you can
  • 01
    Read the table of jobsName the eleven basic jobs every object can do, and the Reflect call that asks for each one.
  • 02
    Spot exotic objectsPredict what arrays, String wrappers, arguments, typed arrays, module namespaces, bound functions, and proxies do in their own special way.
  • 03
    Explain the promisesSay when a proxy's answer breaks a promise, because a property is fixed or the object accepts no new keys.

Objects follow hidden rules

In Function calls: [[Call]] & [[Construct]], you saw that a function is an object that can also be called. This lesson asks a wider question. What does any object do when your code reads a property, changes a prototype, or lists its keys?

The specification answers with internal methods. An internal method is one job that every object knows how to do, such as "read a property". The spec writes its name in double square brackets, like [[Get]]. Your code can't call these names directly. They only describe what happens.

Start with one property readPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
console.log(cart.price);

Line 1 makes a cart object with a price of 3. Line 2 reads cart.price and prints 3. Behind that read, the spec runs the [[Get]] job on the cart. Your code never writes cart.[[Get]]; that name only exists in the spec.

Definition

Most objects do these jobs the usual way. They are called ordinary objects. An exotic object does at least one of the jobs in its own special way. Both kinds must keep the same basic promises, called invariants.

We start with a plain cart. Then we look at objects that do some jobs differently:

  • arrays and String wrappers,
  • the arguments object and typed arrays,
  • module namespaces and bound functions,
  • proxies and Object.prototype.

"Exotic" does not mean strange-looking or rare. It is just the spec's name for an object with a special rule. The ECMAScript object model lists every job and its promises.

The eleven basic jobs of every object

Every object can do the same eleven jobs. The spec calls them the essential internal methods. You can't call them by their bracket names. But JavaScript has a built-in helper object called Reflect. Each Reflect function asks an object to do one of these jobs. That lets us try them out.

Read a price, then check that it existsPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
console.log(Reflect.get(cart, "price"));
console.log(Reflect.has(cart, "price"));

Line 1 makes the cart. Line 2 uses Reflect.get to read the price, and prints 3. Line 3 uses Reflect.has to ask "is there a price here?", and prints true. Reflect.has looks on the cart and also on its prototype, the parent object it borrows from. Reading a value and checking that a key exists are two different jobs.

The table lists all eleven jobs. Read each row as: "this spec name does this job, and this Reflect call asks for it."

The eleven basic jobs every object can do
Spec nameWhat the job doesHow to ask for it in code
[[GetPrototypeOf]]Read the object's parent (its prototype).Reflect.getPrototypeOf(cart)
[[SetPrototypeOf]]Try to change the object's parent.Reflect.setPrototypeOf(cart, null)
[[IsExtensible]]Ask whether the object still accepts new keys.Reflect.isExtensible(cart)
[[PreventExtensions]]Stop the object from accepting new keys.Reflect.preventExtensions(cart)
[[GetOwnProperty]]Read the settings card of a property the object owns.Reflect.getOwnPropertyDescriptor(cart, 'price')
[[DefineOwnProperty]]Try to create or change a property from a new settings card.Reflect.defineProperty(cart, 'price', { value: 4 })
[[HasProperty]]Check for a key on the object or on its parents.Reflect.has(cart, 'price')
[[Get]]Read a value. If the object doesn't have it, look in the parents.Reflect.get(cart, 'price')
[[Set]]Try to write a value, and answer whether it worked.Reflect.set(cart, 'price', 5)
[[Delete]]Try to remove a property the object owns.Reflect.deleteProperty(cart, 'price')
[[OwnPropertyKeys]]List the object's own keys, as strings and symbols.Reflect.ownKeys(cart)
Try all eleven jobs on one cartPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
console.log(Reflect.getPrototypeOf(cart) === Object.prototype);
console.log(Reflect.setPrototypeOf(cart, null));
console.log(Reflect.isExtensible(cart));
console.log(Reflect.preventExtensions(cart));
console.log(Reflect.isExtensible(cart));
console.log(Reflect.getOwnPropertyDescriptor(cart, "price").value);
console.log(Reflect.defineProperty(cart, "price", { value: 4 }));
console.log(Reflect.has(cart, "price"));
console.log(Reflect.get(cart, "price"));
console.log(Reflect.set(cart, "price", 5));
console.log(Reflect.ownKeys(cart).join(","));
console.log(Reflect.deleteProperty(cart, "price"));

The program asks the same cart to do each job in turn:

  • Lines 2 and 3 read the prototype, then change it to null.
  • Lines 4 to 6 ask whether new keys can be added, then block new keys, then ask again. The answer changes from true to false.
  • Lines 7 to 10 read the price's descriptor (its settings card, explained later), give price a new value of 4, check that price exists, and read it.
  • Lines 11 to 13 write 5, list the keys, and delete price.

The program prints true, true, true, true, false, 3, true, true, 4, true, price, true, one value per line. Most Reflect calls print true or false: did the job work? A plain assignment like cart.price = 5 doesn't tell you that. In strict mode, it throws an error instead when the write fails.

Real-life analogyA phone contact list

You open the contacts on your phone. You check that Asha is saved. You read her number. You may change the number. You may also scroll through every saved name. Each of these is a different action on the same list.

In real life: Check if Asha is saved
In JavaScript: [[HasProperty]] checks for a key
In real life: Read Asha's number
In JavaScript: [[Get]] reads a value
In real life: Change the saved number
In JavaScript: [[Set]] tries to write
In real life: List saved contacts
In JavaScript: [[OwnPropertyKeys]] lists own names

Reading a property can look in the parent

Two words first:

  • An own property sits directly on the object itself.
  • A prototype is a parent object. When the object doesn't have a property, JavaScript looks in the parent next.

During the read, JavaScript also remembers the object you started from. The spec calls it the receiver. If the parent has a getter (a function that runs when you read a property), the getter uses the receiver as its this.

Read a price the cart ownsPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
console.log(cart.price);

Line 1 makes a cart with its own price. Line 2 reads it and prints 3. JavaScript finds price on the cart itself, so it doesn't need to look in a parent.

Read a price from a parentPop out in the code editor (opens in a new tab)JavaScript
const parent = { price: 3 };
const cart = Object.create(parent);
console.log(cart.price);
console.log(Object.hasOwn(cart, "price"));

Line 1 makes a parent with a price of 3. Line 2 uses Object.create(parent) to make an empty cart whose prototype is parent. Line 3 reads cart.price. The cart has no price, so JavaScript looks in the parent and prints 3. Line 4 asks Object.hasOwn: "does the cart itself own price?" It prints false.

Reading cart.price. The cart has no price of its own, so JavaScript asks the parent. The parent holds price 3, and the read gives the value 3.cart.pricecartno own priceask parentprice: 3parent3value
The cart has no price of its own, so the read goes on to its parent. The parent has price: 3, so cart.price gives 3.

So Object.hasOwn only looks at the object itself. A read or Reflect.has also looks in the parents.

Next, here is how the specification describes a read. Spec steps read like a recipe. "Let x be …" means "call the result x". A ? means "if this step goes wrong, stop and throw the error". In the box, O is the object, P is the property name, and Receiver is the object you started from.

How a read works: OrdinaryGet, shortened from the specText
1. Let desc be ? O.[[GetOwnProperty]](P).
2. If desc is undefined, let parent be ? O.[[GetPrototypeOf]]().
3. If parent is null, return undefined; otherwise return ? parent.[[Get]](P, Receiver).

In plain words, line by line:

  1. Look for the property on the object itself. Call what you find desc.
  2. If nothing was found, get the object's parent.
  3. If there is no parent, the answer is undefined. Otherwise, ask the parent to do the same read, and keep the receiver.

The full OrdinaryGet steps have one more case. When the property is a getter, JavaScript calls the getter with the receiver as this. The box leaves that case out.

Replay: read a price from the parent
Step 0 of 5Ready
Your turn: follow the blue line

A replay of the real readPrice function. It is not a view inside the engine.

Running in
  1. script
Next: line 1
const cart = Object.create(parent);function readPrice(order) {  return Reflect.get(order, "price");}console.log(readPrice(cart));
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Press Step to walk through the replay. It runs a real readPrice function, which returns 3. You'll see that the cart has no price of its own, and that the read still finds 3 in the parent. Back goes one step back.

Writing a property uses the object you started from

A write is the [[Set]] job. It tries to change a value. It answers true if the write worked and false if it didn't. When the property is found in a parent, the new value is still saved on the object you started from, the receiver. The parent stays the same.

Change one cart pricePop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
cart.price = 4;
console.log(cart.price);

Line 1 makes a cart with a price of 3. Line 2 changes the price to 4. Line 3 reads it again and prints 4. This is the simplest write that works.

A setter in the parent saves onto the cartPop out in the code editor (opens in a new tab)JavaScript
const parent = { set price(value) { this.saved = value; } };
const cart = Object.create(parent);
cart.price = 3;
console.log(cart.saved, Object.hasOwn(parent, "saved"));

A setter is a function that runs when you write to a property. Line by line:

  • Line 1 makes a parent with a setter for price. The setter saves the value in this.saved.
  • Line 2 makes a cart whose parent is parent.
  • Line 3 writes cart.price = 3. The cart has no price, so JavaScript finds the setter in the parent and runs it.
  • Line 4 prints 3 false. Inside the setter, this was the cart, so saved is on the cart. The parent has no saved.

The Reflect lesson shows how to pass a different receiver yourself.

Here is the write in the spec. ownDesc is what JavaScript finds when it looks for the property on the object itself.

How a write works: OrdinarySetWithOwnDescriptor, shortened from the specText
1. Let ownDesc be ? O.[[GetOwnProperty]](P).
2. If ownDesc is undefined, consult the parent; otherwise use the property descriptor.
3. For an accessor descriptor, call its setter with Receiver as this.

In plain words, line by line:

  1. Look for the property on the object itself. Call what you find ownDesc.
  2. If nothing was found, look in the parent. Otherwise, use the settings that were found.
  3. If the property is a setter, call the setter with the receiver as this.

The full write steps also handle a normal value. If that value is marked as not writable, the write answers false and nothing changes.

Replay: change the cart's price
Step 0 of 5Ready
Your turn: follow the blue line

A replay of the real changePrice function. It is not a view inside the engine.

Running in
  1. script
Next: line 1
function changePrice(order, price) {  return Reflect.set(order, "price", price);}console.log(changePrice(cart, 4));console.log(cart.price);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

This replay runs a real changePrice function. Step through it. The write answers true, and then the cart's price reads 4.

Each property has a settings card

A property descriptor is the settings card of one property. It holds the value (or a getter and setter), plus three yes/no settings:

  • writable: can the value be changed?
  • enumerable: does the key show up in lists like Object.keys?
  • configurable: can the property be deleted, or its settings changed?

The [[DefineOwnProperty]] job creates or changes a property from a new settings card. Before it does, it checks the card against the old one. It also checks whether the object still accepts new keys. If the change isn't allowed, Reflect.defineProperty answers false.

Make a price that is hidden from key listsPop out in the code editor (opens in a new tab)JavaScript
const cart = {};
Object.defineProperty(cart, "price", { value: 3, writable: false });
console.log(cart.price, Object.keys(cart).length);

Line 1 makes an empty cart. Line 2 uses Object.defineProperty to add a price of 3 with writable: false. The settings you leave out are false too. Line 3 prints 3 0. The price is there, but Object.keys lists zero keys, because enumerable is false.

Here are the define steps from the spec. Desc is the new settings card, and current is the old one.

How a define works: OrdinaryDefineOwnProperty, shortened from the specText
1. Let current be ? O.[[GetOwnProperty]](P).
2. Let extensible be ? O.[[IsExtensible]]().
3. Return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current).

In plain words, line by line:

  1. Read the property's current settings card. Call it current.
  2. Ask whether the object still accepts new keys. Call the answer extensible.
  3. Compare the new card with the old one, and apply it only if the change is allowed.

So a property called price can't always be replaced. The full define steps list every check.

Playground: allow or block a price change
The code with your settingPop out in the code editor (opens in a new tab)JavaScript
const cart = {};Object.defineProperty(cart, "price", { value: 3, writable: true });console.log(Reflect.set(cart, "price", 4));console.log(cart.price);
What the code prints
Reflect.set answerstrue
cart.price is4
Try it yourself

Reflect.set answers true. The price is now 4. Only the writable setting changes.

This runs the real Object.defineProperty and Reflect.set. Reset ticks the box again.

The box starts ticked, and the code prints true then 4. Untick it, and the code prints false then 3. Only writable changes. Reset ticks the box again.

Arrays and String wrappers have special indexes

An array is an exotic object. The spec calls it an Array exotic object. Its special rule ties the numbered keys (the indexes) to its length:

  • Writing at an index past the end makes length bigger.
  • Making length smaller deletes the items above the new length.
  • A gap in an array is called a hole. A hole is a missing key. It is not a stored undefined.
Leave one hole in an arrayPop out in the code editor (opens in a new tab)JavaScript
const cart = ["tea"];
cart[2] = "water";
console.log(cart.length, 1 in cart);

Line 1 makes an array with "tea" at index 0. Line 2 puts "water" at index 2. Nothing is put at index 1. Line 3 prints 3 false. The length is 3, one more than the last index. But 1 in cart is false, because index 1 is a hole.

An array drawn as three boxes. Box 0 holds tea. Box 1 is empty. Box 2 holds water. The length is 3.length: 3tea01water2empty
Line 2 puts "water" at index 2, so length becomes 3. Nothing was ever put at index 1, so 1 in cart is false.
Making length smaller removes later itemsPop out in the code editor (opens in a new tab)JavaScript
const cart = ["tea", "milk", "water"];
cart.length = 1;
console.log(cart.length, cart[2]);

Line 1 makes an array with three items. Line 2 sets length to 1. Line 3 prints 1 undefined, because the items at index 1 and 2 were deleted. If one of those items can't be deleted, the length stops just above it. So length is a real property with its own rules. It isn't worked out again on every read.

Here is the special define step for arrays. P is the key being defined, and A is the array.

How an array defines a key, shortened from the specText
1. If P is "length", return ArraySetLength(A, Desc).
2. If P is an array index, define the property, then update "length" if necessary.

In plain words, line by line:

  1. If the key is "length", use the special length steps. They can delete items.
  2. If the key is an index, add the item, then make length bigger if needed.

The full array define steps have more detail. For everyday array work, see the Arrays lesson.

A String wrapper is an object made around a string with new String(...). The spec calls it a String exotic object. Each character shows up as an own property at an index. These properties are fixed: you can't change them or delete them. A plain string lets you read characters by index too, but the wrapper object makes the properties easy to look at.

Look at a String wrapper's indexesPop out in the code editor (opens in a new tab)JavaScript
const word = new String("tea");
console.log(word[0], Object.keys(word).join(","));

Line 1 wraps the string "tea". Line 2 reads index 0 and lists the keys. It prints t 0,1,2: one key for each character. Your code didn't add these keys. The wrapper makes them itself.

A character can't be changed or removedPop out in the code editor (opens in a new tab)JavaScript
const word = new String("tea");
console.log(Object.getOwnPropertyDescriptor(word, "0").writable);
console.log(Reflect.deleteProperty(word, "0"));

Line 1 makes the same wrapper. Line 2 reads the settings card of index 0 and prints false for writable. Line 3 tries to delete index 0 and prints false: the delete didn't work. The spec's String [[GetOwnProperty]] steps build these settings cards for each character.

The arguments object and typed arrays

Inside a normal function, arguments is an object that holds every value passed in. In some functions, arguments[0] and the first parameter are linked: change one, and the other changes too. The spec calls this a mapped arguments object. The link exists only when both are true:

  • the function is not in strict mode, and
  • its parameters are simple names, with no default values, no ...rest, and no destructuring.

Deleting arguments[0] also breaks the link for that index.

Without strict mode, the parameter follows arguments[0]Pop out in the code editor (opens in a new tab)JavaScript
function order(item) {
  arguments[0] = "coffee";
  console.log(item);
}
order("tea");

Line 5 calls order("tea"). Line 1 receives tea in the parameter item. Line 2 changes arguments[0] to "coffee". Line 3 prints item, and it prints coffee, because the two are linked. This example has no "use strict" line on purpose.

In strict mode, the parameter stays the samePop out in the code editor (opens in a new tab)JavaScript
function order(item) {
  "use strict";
  arguments[0] = "coffee";
  console.log(item);
}
order("tea");

Line 2 turns on strict mode for the function. Line 3 still changes arguments[0]. But line 4 prints tea, because in strict mode item and arguments[0] are not linked.

Left, not strict: the tags item and arguments[0] both point to one value card, coffee. Right, strict mode: item points to tea and arguments[0] points to coffee.not strictitemarguments[0]coffeesharedstrict modeitemarguments[0]teacoffee
Without strict mode, item and arguments[0] share one value, so both say coffee. In strict mode they are separate, so item stays tea.
Deleting arguments[0] breaks the linkPop out in the code editor (opens in a new tab)JavaScript
function order(item) {
  delete arguments[0];
  arguments[0] = "coffee";
  console.log(item);
}
order("tea");

This function is not in strict mode. Line 2 deletes arguments[0]. Line 3 adds a new arguments[0]. Line 4 prints tea, because the new property isn't linked to item. The spec's arguments object steps keep a list of which indexes are still linked.

A typed array, such as Uint8Array, holds numbers of one fixed kind. A Uint8Array holds whole numbers from 0 to 255, one byte each. Its length is fixed when you make it. The spec calls it an integer-indexed exotic object. Its rules for number keys are special:

  • A number key past the end never adds an item.
  • A value that doesn't fit is changed into one that does.
  • Keys that aren't numbers work like on a plain object.
A typed array doesn't growPop out in the code editor (opens in a new tab)JavaScript
const scores = new Uint8Array([3]);
console.log(Reflect.set(scores, "1", 4), scores.length);
console.log(Reflect.defineProperty(scores, "1", { value: 4 }));

Line 1 makes a typed array with one item, 3. Line 2 tries to write at index 1, past the end. It prints true 1. Reflect.set answers true, but the length is still 1: no item was added. Line 3 tries to define index 1 and prints false.

So these two calls answer differently for the same missing index. A true from Reflect.set does not prove that an item was added.

A value is changed to fit in one bytePop out in the code editor (opens in a new tab)JavaScript
const scores = new Uint8Array([3]);
scores[0] = 259;
console.log(scores[0], Reflect.deleteProperty(scores, "0"));

Line 1 makes the typed array. Line 2 stores 259 at index 0. One byte can only hold 0 to 255, so 259 wraps around and becomes 3. Line 3 prints 3 false: the value is 3, and the item at index 0 can't be deleted. The spec's typed array rules treat an existing index and an index past the end differently.

Module namespaces and bound functions

import * as cart from "./cart.mjs" gives you one object that holds everything the file exports. This object is a module namespace object, another exotic object. Its rules:

  • It has one key for each export name. You can't add, remove, or replace keys.
  • Each read gives the export's value right now. If the other file changes the value, the next read sees the change.
  • It has no prototype: its prototype is null.
Read a module namespace, main.mjsJavaScript
import { price } from "./cart.mjs";
import * as cart from "./cart.mjs";
console.log(cart.price, Object.isExtensible(cart));

Line 1 imports price by name. Line 2 imports the whole namespace as cart. Line 3 reads cart.price and asks whether cart accepts new keys. It prints 4 false. The file below changed its price to 4 before this line runs. Modules can't run in the lesson editor, so this box has no Run button.

The file that exports price, cart.mjsJavaScript
export let price = 3;
price = 4;

Line 1 exports price with the value 3. Line 2 changes it to 4. The namespace key price stays the same, but reading it gives the newest value, 4. The importing file still can't assign a new value to cart.price. See Module Records for how modules connect.

bind makes a new function from an old one. The new one is a bound function, also exotic. It remembers three things:

  • the original function, called the target,
  • the value to use as this,
  • any first arguments to pass in.

When you call it, it calls the target with those saved values. When you use it with new, it ignores the saved this and makes a fresh object instead.

Bind one order to AshaPop out in the code editor (opens in a new tab)JavaScript
function order(item) { return this.name + ":" + item; }
const serve = order.bind({ name: "Asha" }, "tea");
console.log(serve());

Line 1 makes a function that joins this.name and an item. Line 2 binds it to an object with the name Asha, and to the first argument "tea". Line 3 calls the bound function with no arguments, and it prints Asha:tea. This is the special [[Call]] job of a bound function.

Use new with a bound functionPop out in the code editor (opens in a new tab)JavaScript
function Order(item) { this.item = item; }
const TeaOrder = Order.bind(null, "tea");
console.log(new TeaOrder().item);

Line 1 makes a constructor that saves an item on the new object. Line 2 binds null as this and "tea" as the first argument. Line 3 uses new and prints tea. The saved null is ignored; the new object is used as this. If the target can't be used with new, binding it doesn't change that.

Proxies step in; Object.prototype keeps its parent

A Proxy wraps another object, called the target. You give it a handler object with functions called traps. When a job such as a read happens on the proxy, the matching trap runs instead. But the target still sets limits on what a trap may answer. The Proxy and Reflect lessons cover every trap.

A proxy that passes a read straight throughPop out in the code editor (opens in a new tab)JavaScript
const cart = new Proxy({ price: 3 }, {
  get(target, key, receiver) { return Reflect.get(target, key, receiver); },
});
console.log(cart.price);

Line 1 makes a proxy around a target object with a price of 3. Line 2 is the get trap. It passes the read on to the target with Reflect.get, using the same target, key, and receiver. Line 4 reads cart.price through the proxy and prints 3. A trap that only passes the job on keeps the usual result.

A proxy can't give a wrong answer for a frozen pricePop out in the code editor (opens in a new tab)JavaScript
const cart = Object.freeze({ price: 3 });
const proxy = new Proxy(cart, { get() { return 4; } });
try {
  console.log(proxy.price);
} catch (error) {
  console.log(error.name);
}

Line 1 freezes a cart with a price of 3. Frozen means the price can't be changed or deleted. Line 2 makes a proxy whose get trap always answers 4, which is wrong. Line 4 reads proxy.price. JavaScript checks the answer against the frozen cart and throws a TypeError. Line 6 catches it and prints its name. The try and catch keep the program running after the error.

Reading proxy.price. The get trap says 4. The frozen cart holds price 3. The two answers do not match, so the read throws TypeError.proxy.pricetrap says 4does notmatchprice: 3cartfrozenTypeError
The trap says 4, but the frozen cart holds 3. JavaScript checks the trap's answer against the cart and throws a TypeError.

Here are the proxy read steps from the spec. trap is the get function, handler is the object that holds it, and P is the property name.

How a proxy read is checked, shortened from the specText
1. Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
2. Let targetDesc be ? target.[[GetOwnProperty]](P).
3. If targetDesc is non-configurable and non-writable, check trapResult against its value.

In plain words, line by line:

  1. Call the trap with the target, the property name, and the receiver. Call its answer trapResult.
  2. Read the target's own settings card for the property. Call it targetDesc.
  3. If the property can't be changed or deleted, the trap's answer must equal the real value. If not, throw a TypeError.

The full proxy read steps check one more case, for getters. The other traps have their own checks too.

Some objects refuse to change their prototype. The spec calls them immutable prototype exotic objects. Object.prototype is the one you meet every day. Asking it to keep its current prototype works. Asking it to take a different one fails. This is not the same as Object.freeze, which locks an object's own properties and blocks new ones.

Object.prototype refuses a new prototypePop out in the code editor (opens in a new tab)JavaScript
const cart = Object.prototype;
console.log(Reflect.setPrototypeOf(cart, null));
console.log(Reflect.setPrototypeOf(cart, {}));

Line 1 names Object.prototype as cart. Its prototype is null. Line 2 asks it to keep null and prints true, because nothing changes. Line 3 asks for a different object, {}, and prints false. The spec's immutable prototype rule says exactly this.

The promises every object keeps

An invariant is a promise that every object's jobs must keep. Exotic objects can do a job in a special way, but they still keep these promises. Two examples:

  • If an object no longer accepts new keys, it can't gain a new own property, and it can't change its prototype.
  • A property that can't be deleted can't go missing from the object's list of keys.
A key that can't be deleted can't be hiddenPop out in the code editor (opens in a new tab)JavaScript
const cart = Object.preventExtensions({ price: 3 });
const proxy = new Proxy(cart, { ownKeys() { return []; } });
try {
  console.log(Reflect.ownKeys(proxy));
} catch (error) {
  console.log(error.name);
}

Line 1 makes a cart with a price, then blocks new keys with Object.preventExtensions. Line 2 makes a proxy whose ownKeys trap says the cart has no keys at all, which is wrong. Line 4 asks for the keys. JavaScript compares the trap's empty list with the real cart and throws a TypeError. Line 6 catches it and prints TypeError.

The table shows five of these promises. Read each row as: "when a property or object is like this, this must stay true, and here is an example that breaks it."

Five promises the object jobs must keep
When it isWhat must stay trueWhat breaks the promise
The object accepts no new keys.Its parent can't change, and no new own key can appear.A proxy that reports an extra key, or leaves out a real one.
A property is fixed: it can't be deleted or have its settings changed.The key can't go missing from the key list or from its settings card.A proxy that hides a frozen price.
A property is fixed, and its value can't be changed.A read must give the real value.A get trap that says 4 when the frozen price is 3. The read throws.
A property is fixed, works through functions instead of a stored value, and has no setter.A write can't claim that it worked.A set trap that answers true for that property.
Listing the own keys.Each key appears once, as a string or a symbol.A list with the same key twice, or with a number in it.

Each job has its own promises. The main ones, in plain words:

  • [[GetOwnProperty]] can't say a fixed property is gone.
  • [[DefineOwnProperty]] can't add a key to an object that no longer accepts new keys.
  • [[GetPrototypeOf]] must answer with an object or null. If the object no longer accepts new keys, the answer must be its real prototype.
  • [[SetPrototypeOf]] may refuse. It can't claim it changed the prototype of an object that no longer accepts new keys.
  • [[IsExtensible]] on a proxy must give the target's real answer. After [[PreventExtensions]] says it worked, that answer must be false.
  • [[HasProperty]] can't hide a fixed key, and [[Delete]] can't claim it removed one.
  • [[Get]] can't give a wrong value for a frozen property, and [[Set]] can't claim it changed one. For a fixed property with no getter, [[Get]] must answer undefined. For one with no setter, [[Set]] can't claim the write worked.
  • [[OwnPropertyKeys]] must list each key once, as a string or symbol, and include every fixed key.

Use the right tool in app code

Say a settings page saves a value, and it needs to know whether the save worked. Reflect.set answers true or false. A plain assignment like settings.theme = "dark" doesn't tell you. In strict mode, it throws an error when the write fails. Pick the tool that answers your question.

Check whether a cart update workedPop out in the code editor (opens in a new tab)JavaScript
const cart = { price: 3 };
console.log(Reflect.set(cart, "price", 4));
console.log(cart.price);

Line 1 makes a cart. Line 2 tries to change the price to 4 and prints true: the write worked. Line 3 reads the price and prints 4. "Did the write work?" and "what is the value now?" are two different questions.

The table lists each kind of object from this lesson. Read each row as: "this kind of object has this special rule, and here is where you'd see it."

Kinds of objects and their special rules
Kind of objectIts special ruleWhere you see it
Ordinary objectIt does every job the usual way.A plain cart object.
ArrayWriting past the end makes length bigger. Making length smaller deletes the later items.cart[2] = "water" or cart.length = 1.
String wrapperEach character is a fixed own property at an index.new String("tea")[0]
Linked argumentsWithout strict mode and with simple parameters, arguments[0] and the first parameter change together.Changing arguments[0] also changes item.
Typed arrayNumber keys only reach items that exist. It never grows, and values are changed to fit.scores[0] in a Uint8Array.
Module namespaceIts keys are the export names, and they can't change. Each read gives the newest export value.import * as cart from "./cart.mjs"
Bound functionA call uses the saved function, the saved this value, and the saved first arguments.order.bind(user, "tea")
ProxyA trap can step in for a job, but its answer must keep the target's promises.new Proxy(cart, handler)
Object with a fixed parentIt refuses to change its prototype to a different object.Object.prototype

On a website, these rules help in a few places:

  • proxies that check form input,
  • settings that can or can't be changed,
  • settings imported from another file,
  • byte data in typed arrays.

Use Object.hasOwn when only the object's own keys count. Use Reflect.has when keys from parents count too. Read the settings card with Object.getOwnPropertyDescriptor before you assume a property can be changed or deleted.

Sort the objects
  • A plain { price: 3 }
  • An object made with Object.create(parent)
  • An array, whose length changes with its indexes
  • A String wrapper with one key per character
  • A Uint8Array that never grows
  • A Proxy with a get trap
  • An imported module namespace
Try it yourself
0 of 7 correct

Put each object in a group: ordinary, exotic with special indexes, or another kind of exotic.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

A bracket name like [[Get]] names a job in the spec. It is not a method you can call. "Exotic" is the spec's word for an object with a special rule. It does not mean "complicated". A plain object with a getter is still ordinary: the usual [[Get]] job is what runs the getter.

  • "Every exotic object is a Proxy." Arrays, String wrappers, the arguments object, and module namespaces each have their own rules.
  • "Array length counts the items." An array can have holes. Its length can be 3 while index 1 is missing.
  • "arguments always follows the parameters." The link only exists without strict mode and with simple parameters. Deleting an index breaks it.
  • "If Reflect.set says true, the value changed." A typed array answers true for an index past its end, but adds nothing.
  • "A Proxy can answer anything." The target's fixed properties, and whether it accepts new keys, still limit the traps.

The table compares words that sound alike. Read each row as: "this word means this, and it is not that."

Words that sound alike but mean different things
WordWhat it meansWhat it does not mean
[[Get]]A job named in the spec. JavaScript runs it when your code reads a property.It is not a method you can call, like cart.[[Get]]().
ExoticAn object that does at least one job in its own special way.It doesn't mean slow, rare, or strange-looking.
Array lengthA real property that grows when you write at an index past the end.It doesn't count the items. An array with a hole still has the full length.
Typed-array indexA number key that reaches one item of a typed array.It never makes the typed array grow, the way writing past the end grows a normal array.
Proxy trapA function that steps in for one job. JavaScript checks its answer against the target.It can't give any answer it likes.

Two more mix-ups. A module namespace reads the newest export value, but the importing file still can't assign to it. A bound function works with new only if the original function does. For every example, first name the kind of object. Then predict what it does.

Practice exercises

For each exercise, first guess what the code prints. Then name the rule that explains it: a settings card, an index rule, or a proxy's target. The last exercise checks a save on a real website's settings.

Exercise 1 · Warm-upPredict an array shrink

A shopping cart removes its last item by making length smaller. What does the code print? Type both values in order.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const cart = ["tea", "milk"];
cart.length = 1;
console.log(cart[1], cart.length);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict a mapped parameter

    The order function receives tea, then changes arguments[0]. Which item does it print? Then say why strict mode would print something else.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function order(item) {
      arguments[0] = "coffee";
      console.log(item);
    }
    order("tea");

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeAllow a price update

      A cart should let its price change. Which one setting in the starter code must you change? Name it, then run the worked solution.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const cart = {};
      Object.defineProperty(cart, "price", { value: 3, writable: false });
      console.log(Reflect.set(cart, "price", 4));

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeConvert a typed-array byte

        A score is kept in a one-byte typed array. The code stores 259 at index 0, which already exists. What does it print?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const scores = new Uint8Array([3]);
        scores[0] = 259;
        console.log(scores[0]);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFind the broken proxy promise

          A proxy tries to hide a key of a cart. What error name is printed? Then explain why an empty key list doesn't match the real cart.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const cart = Object.preventExtensions({ price: 3 });
          const proxy = new Proxy(cart, { ownKeys() { return []; } });
          try { Reflect.ownKeys(proxy); } catch (error) { console.log(error.name); }

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeUpdate a website setting

            A website saves a theme choice in a settings object. Which two values does the code print? In a real app, check the true before you show a "Saved" message.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const settings = { theme: "light" };
            console.log(Reflect.set(settings, "theme", "dark"), settings.theme);

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, first decide what it asks about: a key on the object itself, a read, a write that worked, or a special rule. For code questions, guess what the code prints before you name the job behind it.

              Internal methods and exotic objects quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Which job reads a value, and looks in the parent when the object doesn't have it?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this code print after the array's length is set to 1?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const cart = ["tea", "milk"];
                cart.length = 1;
                console.log(cart[1], cart.length);

                Choose an answer to see the explanation.

              3. Question 3 of 7When are arguments[0] and the first parameter linked?

                Choose an answer to see the explanation.

              4. Question 4 of 7What does this typed array print after 259 is stored?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const scores = new Uint8Array([3]);
                scores[0] = 259;
                console.log(scores[0]);

                Choose an answer to see the explanation.

              5. Question 5 of 7A proxy's ownKeys trap leaves out a key of a cart that accepts no new keys. What is printed?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const cart = Object.preventExtensions({ price: 3 });
                const proxy = new Proxy(cart, { ownKeys() { return []; } });
                try { Reflect.ownKeys(proxy); } catch (error) { console.log(error.name); }

                Choose an answer to see the explanation.

              6. Question 6 of 7Which sentence describes a module namespace object?

                Choose an answer to see the explanation.

              7. Question 7 of 7What does Reflect.set answer for a property whose value can't be changed?

                Choose an answer to see the explanation.

              Key takeaways

              The bracket names give you words for things you can see your code do. For any object, start with the usual rule. Then ask: is this object exotic, and which job does it do differently?

              • Every object can do eleven basic jobs: for prototypes, for accepting new keys, for settings cards, and for checking, reading, writing, deleting, and listing keys.
              • A read can look in the parent. A write saves on the object you started from. A define checks the settings card first.
              • Arrays tie indexes to length. String wrappers have fixed characters. Without strict mode, arguments[0] can be linked to a parameter.
              • Typed arrays never grow, and they change values to fit. A module namespace always reads the newest export value.
              • Bound functions remember what to call with. Proxies can step in, but they can't break the target's promises.

              Remember the one-liner.
              An exotic object does some jobs in its own way, but it keeps the same promises as every other object.

              Coming next: A tour of the abstract operations. These are the shared steps the spec uses to convert values, compare them, and loop over them.

              CompleteFrontend Clear concepts. Working examples.