completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

How to read ECMAScript

Learn to navigate the ECMAScript specification, follow abstract operations and algorithm steps, and read internal slots, methods, and error notation.

By the end, you can
  • 01
    Find a ruleStart from a line of JavaScript and find the spec rules that explain what it does.
  • 02
    Read the notationTell spec rules apart from JavaScript you can run, and read [[ ]] names and the ? and ! marks.
  • 03
    Explain an outputUse a few spec steps to predict keys, reads through a prototype, and errors.

A guide to the language rules

You already know how to use JavaScript. This lesson shows you how to find the written rule behind something JavaScript does. All the rules live in one long document called ECMAScript. It is the official standard for JavaScript. People often call it the spec, short for specification.

The spec says what every JavaScript engine must do. An engine is the program that runs your code, such as V8 in Chrome. The spec is not the engine's own code. It only says what the result must be.

One property read we want to explainPop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };console.log(cart.tea);

Line 1 makes a cart object. Its tea property holds 3. Line 2 reads cart.tea and prints 3. The spec says what this read must do. Two engines may do the work in different ways, but both must print 3.

The main idea

A spec algorithm is a short list of numbered steps that says what JavaScript must do. To use one, start from code you can run. Follow only the steps that code uses. Then check the result it prints.

The previous lesson, JavaScript & WebAssembly, looked inside the engine. This lesson is different. A spec rule says what must happen. It does not say how the engine does it. You don't need to read the whole spec first. One rule at a time is enough.

Find your way around the spec

Start with a small question: why does a value change type? In the code below, the text "3" turns into a number before the addition. To find the rule, search the spec for the built-in function you used, Number. Then follow its link to the conversion rule.

Text turns into a numberPop out in the code editor (opens in a new tab)JavaScript
const price = "3";console.log(Number(price) + 2);

Line 1 stores the text "3", not a number. Line 2 calls Number(price) to get the number 3. Then it adds 2, so it prints 5.

Number hands the work to a named conversion rule. The spec calls a named rule like this an abstract operation. You'll meet them properly two sections below.

The spec has a few main kinds of rules. Read each row of the table as: "this kind of rule answers this question, for example …"

The main kinds of rules in the spec
Kind of ruleQuestion it answersExample
Syntax (grammar)Which ways of writing code are allowed?A declaration such as const price = 3.
Static SemanticsWhat can be worked out from the code without running it?StringValue gives a name as it is written.
Runtime SemanticsWhat happens when the code runs?Evaluation finds a variable's value or reads a property.
Abstract operationsWhich named steps do other rules use again and again?ToPropertyKey turns the value in cart[key] into a key.

The spec is split into chapters. There are chapters for value types, named rules, objects, expressions, statements, and built-in functions. Two more words help you find your way:

  • A grammar production is a written pattern that code can match, such as "a const declaration".
  • A rule headed Static Semantics looks at that pattern without running it. A rule headed Runtime Semantics says what happens when it runs.

To find a rule, open the ECMAScript spec, split into pages. Search for a heading or a rule name, then follow its links. Don't rely on chapter numbers: they can change between editions.

For cart.tea, begin at Property Accessors. That is the rule for reading a property with a dot or with square brackets. For a key in square brackets, such as cart[key], follow the links to GetValue and ToPropertyKey. Stop once a few steps explain your output. You don't need every rule on the page.

Read one step at a time

A spec algorithm reads like a short recipe. Each step starts with a key word:

  • Let gives a result a name. "Let key be …" means "call the result key".
  • If chooses which path to take.
  • Return finishes the steps and hands back a result.
  • Assert: states something that is already sure to be true at that point. It is a note for the reader. It never prints anything on your page.
Turn values into text with String()Pop out in the code editor (opens in a new tab)JavaScript
const price = 3;console.log(String(price));console.log(String(undefined));

Line 1 stores the number 3. Line 2 turns it into the text "3" and prints it. Line 3 turns undefined into the text "undefined" and prints it.

The console shows the number 3 and the text "3" the same way. To tell them apart, use typeof. It gives a value's type as text, such as "number" or "string".

Below are a few steps from the spec's ToString rule. ToString is the rule that turns any value into text. The box is spec text, not a program you can run.

How ToString works: a few of its steps, from the specText
ToString ( arg )
1. If arg is a String, return arg.
2. If arg is a Symbol, throw a TypeError exception.
3. If arg is undefined, return "undefined".

In plain words, line by line:

  1. The rule is called ToString. It takes one input, named arg.
  2. If arg is already text (a String), hand it back unchanged.
  3. If arg is a Symbol, throw a TypeError. A Symbol is a special one-of-a-kind value; you'll meet one below.
  4. If arg is undefined, hand back the text "undefined".

The name arg belongs to the spec, not to our program. The box shows only some steps. The full rule also covers numbers, objects, and other values.

Also, String(...) in JavaScript is not the same thing as ToString. For example, String(Symbol("tea")) gives the text "Symbol(tea)", but ToString throws for a Symbol.

Abstract operations are reusable steps

An abstract operation is a named list of steps in the spec. Other rules use it again and again. It has a name and inputs, like a function. But it is not a JavaScript function: you can't call it from your code.

For example, ToPropertyKey turns a value into a property key. A property key is the name an object uses to find one of its properties.

A number as a property namePop out in the code editor (opens in a new tab)JavaScript
const cart = { 3: "tea" };console.log(cart[3]);console.log(cart["3"]);

Line 1 makes an object with "tea" stored under the key 3. Line 2 reads it with the number 3 and prints tea. Line 3 reads it with the text "3" and also prints tea.

Both lines find the same property. An object's keys are always text or Symbols, so the number 3 becomes the text "3".

The number 3 goes through ToPropertyKey and comes out as the text "3". The cart keeps tea under the name "3".3numberToPropertyKey"3"text"3": "tea"cart
In cart[3], ToPropertyKey turns the number 3 into the text "3". The cart keeps tea under "3", so cart[3] and cart["3"] find the same tea.

Here are the exact steps of ToPropertyKey. You'll see two new marks. A ? means "if this step fails, stop and pass the error on". A ! means "this step can't fail here". A later section explains both.

How ToPropertyKey works, from the specText
ToPropertyKey ( arg )
1. Let key be ? ToPrimitive(arg, STRING).
2. If key is a Symbol, return key.
3. Return ! ToString(key).

In plain words, line by line:

  1. The rule is called ToPropertyKey. Its input is named arg.
  2. Turn arg into a primitive: a simple value such as a number, text, or Symbol. STRING means "prefer text if there is a choice". Call the result key.
  3. If key is a Symbol, use it as it is.
  4. Otherwise, turn key into text with ToString, and use that text.

So a number such as 3 always ends up as the text "3".

Another abstract operation, Call, runs a function. First it checks that the value really can be called. Then it runs the function through its hidden [[Call]] part. Double square brackets mark hidden parts that only the spec can see; a later section explains them.

Call is a spec rule. It is not a method named Call that you can add to a function.

A function you can callPop out in the code editor (opens in a new tab)JavaScript
function total(price) {  return price + 2;}console.log(total(3));

Line 1 makes a function called total with one input, price. Line 2 returns price + 2. Line 4 calls it with 3 and prints 5.

The Call steps below only check that total can be called, and then start it. The adding happens inside the function.

How Call works: a few of its steps, from the specText
Call ( func, thisValue [ , argList ] )
1. If argList is not present, set argList to a new empty List.
2. If IsCallable(func) is false, throw a TypeError exception.
3. Return ? func.[[Call]](thisValue, argList).

In plain words, line by line:

  1. The rule is called Call. Its inputs are the function func, the value to use as this, and a list of arguments. The square brackets around the list mean it can be left out.
  2. If no list of arguments was given, use an empty list.
  3. If func can't be called, throw a TypeError.
  4. Run func through its hidden [[Call]] part and hand back what it returns. The ? passes on any error.

Follow ToPropertyKey through a real value

A number is easy to turn into a key. An object is different: it can choose how it turns into a primitive. It does that with a special method named [Symbol.toPrimitive]. JavaScript calls this method when it needs a simple value from the object.

JavaScript also passes the method a hint. A hint is a word that says which kind of value it would like, such as "string" or "number".

An object used as a keyPop out in the code editor (opens in a new tab)JavaScript
const cart = {};const key = {  [Symbol.toPrimitive](hint) {    console.log(hint);    return 3;  },};cart[key] = "tea";console.log(cart["3"]);

Line 1 makes an empty cart. Lines 2 to 7 make a key object with that special method. Line 8 uses key inside square brackets. Before storing anything, JavaScript calls the method. Line 4 prints the hint, string, and line 5 returns 3. Then "tea" is stored under the key "3".

Line 9 reads cart["3"] and prints tea. So the output is two lines: string, then tea.

Now match this to the ToPropertyKey steps above:

  • Step 1 asks the object for a primitive, with the hint "string". The object returns 3.
  • Step 2: 3 is not a Symbol, so move on.
  • Step 3: ToString turns 3 into the key "3".

A Symbol takes the other path, at step 2.

A Symbol stays a SymbolPop out in the code editor (opens in a new tab)JavaScript
const key = Symbol("tea");const cart = { [key]: 3 };console.log(cart[key]);console.log(cart["Symbol(tea)"]);

Line 1 makes a Symbol with the description "tea". A description is only a label to help you when you debug. Line 2 stores 3 under that Symbol. Line 3 reads with the Symbol and prints 3.

Line 4 reads with the text "Symbol(tea)" and prints undefined. That text is a different key. A Symbol key never turns into text.

Step through an object used as a key
Step 0 of 8Ready
Your turn: follow the blue line

This replays the lesson's example code. It does not show the engine's hidden data.

Running in
  1. script
Next: line 1
const key = { [Symbol.toPrimitive](hint) {  console.log(hint);  return 3;} };cart[key] = "tea";console.log(cart["3"]);
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 step-through runs the lesson's example and saves a snapshot at each step. It is not a look inside the engine. Watch three things: the hint, the value the method returns, and the final read. Back takes you to an earlier step.

Real-life analogyA phone contact list

You look up a person by the name saved in your phone. A friend says "call Ash". First you work out that Ash means Asha. Then you find Asha in the list.

In real life: You find a person by the name saved in your phone
In JavaScript: An object finds a value by its key
In real life: The name must match the saved name exactly
In JavaScript: The key must match exactly, after it becomes text
In real life: A nickname works once you know whose name it is
In JavaScript: An object works as a key once it becomes a primitive

Now change one input yourself. The playground takes your text as the key, stores "tea" under it, and reads it back. It only uses text keys. It does not call a [Symbol.toPrimitive] method.

Playground: change the key
Starting code: the key is 3Pop out in the code editor (opens in a new tab)JavaScript
const key = "3";const cart = {};cart[key] = "tea";console.log(cart[key]);
Result for your key
key"3"
cart[key]tea
Try it yourself

The code stores tea under the key "3". Then it reads tea back with the same key.

This playground only uses text keys. It does not call a [Symbol.toPrimitive] method. Reset puts back 3.

Internal slots describe hidden state

An internal slot is a hidden piece of data that the spec says an object has. Its name is written in double square brackets.

For example, every ordinary object has a [[Prototype]] slot. It holds the object's prototype: another object that JavaScript searches when a property is missing. You can't read a slot by typing its name with the brackets.

Read tea through the prototypePop out in the code editor (opens in a new tab)JavaScript
const shared = { tea: 3 };const cart = Object.create(shared);console.log(cart.tea);

Line 1 makes shared with tea: 3. Line 2 uses Object.create(shared) to make a new, empty cart whose prototype is shared. Line 3 prints 3. cart has no tea of its own, so JavaScript follows the hidden link to shared.

Reading cart.tea. Step 1: the cart has no tea. Step 2: the read follows the hidden [[Prototype]] link to shared, which holds tea: 3.cart.teacart1. no tea here[[Prototype]]hidden linktea: 3shared2. tea found: 3
cart has no tea of its own. The read follows the hidden [[Prototype]] link to shared and finds 3.

The step below comes from OrdinaryGetPrototypeOf, the rule that hands back an object's prototype. Each engine may store the link in its own way. It only has to behave the way the spec says.

How OrdinaryGetPrototypeOf works, from the specText
OrdinaryGetPrototypeOf ( obj )
1. Return obj.[[Prototype]].

In plain words, line by line:

  1. The rule is called OrdinaryGetPrototypeOf. Its input is an object, named obj.
  2. Hand back whatever is in the object's hidden [[Prototype]] slot.
A property named [[Prototype]] is not the slotPop out in the code editor (opens in a new tab)JavaScript
const shared = { tea: 3 };const cart = Object.create(shared);cart["[[Prototype]]"] = "label";console.log(Object.getPrototypeOf(cart) === shared);console.log(cart["[[Prototype]]"]);

Lines 1 and 2 make shared and link cart to it, as before. Line 3 adds a normal property whose name is the text "[[Prototype]]".

Line 4 uses Object.getPrototypeOf, a built-in function that hands back an object's prototype. It prints true: the real prototype is still shared. Line 5 prints label, the normal property made on line 3.

Watch out for one more name. Functions have a normal property called .prototype. It is a different thing from the function's own [[Prototype]] slot. Keeping these names apart avoids a very common mistake.

Internal methods describe what objects do

An internal method is a hidden behaviour the spec says an object has. Its name is also in double square brackets. For example, [[Get]] says how an object reads a property.

Ordinary objects all use the same steps for [[Get]], called OrdinaryGet. Some special objects can have their own [[Get]] steps. One example is a Proxy: an object that wraps another object and can step in when you use it. You'll see one near the end.

Read tea from the prototype, then from the cartPop out in the code editor (opens in a new tab)JavaScript
const shared = { tea: 3 };const cart = Object.create(shared);console.log(cart.tea);cart.tea = 5;console.log(cart.tea);

Line 1 stores tea: 3 on shared. Line 2 makes cart with shared as its prototype. Line 3 prints 3, found on the prototype. Line 4 gives cart its own tea of 5. Line 5 prints 5. So the output is 3, then 5.

The steps below come from OrdinaryGet. They explain both reads. The box stops before the part about getters, which the full rule also covers.

How OrdinaryGet works: a few of its steps, from the specText
OrdinaryGet ( obj, propertyKey, receiver )
1. Let propertyDesc be ? obj.[[GetOwnProperty]](propertyKey).
2. If propertyDesc is undefined, then
  a. Let parent be ? obj.[[GetPrototypeOf]]().
  b. If parent is null, return undefined.
  c. Return ? parent.[[Get]](propertyKey, receiver).
3. If IsDataDescriptor(propertyDesc) is true, return propertyDesc.[[Value]].

In plain words, line by line:

  1. The rule is called OrdinaryGet. Its inputs are the object obj, the key to find, and the receiver: the object the read started from. The receiver matters for getters; you'll see why below.
  2. Look for a property with this key on obj itself. Call what you find propertyDesc, a short note that describes the property.
  3. If there is no such property, do steps a to c:
  4. a. Get the object's prototype. Call it parent.
  5. b. If there is no prototype (it is null), hand back undefined.
  6. c. Otherwise, do the same read on parent, with the same key and the same receiver.
  7. If the property holds a plain value, hand back that value.

For line 3, cart has no tea, so the read moves on to shared and finds 3. For line 5, cart has its own tea, so the read never goes to the prototype. It hands back 5.

Step through a read from the prototype
Step 0 of 6Ready
Your turn: follow the blue line

This replays the lesson's example code. It does not show the engine's own [[Get]] steps.

Running in
  1. script
Next: line 1
const cart = Object.create(shared);console.log(cart.tea);cart.tea = 5;console.log(cart.tea);
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.

The step-through calls the lesson's own functions for the two reads and shows their real results. It shows the example's lines, not hidden steps inside an engine. Step through the first read before line 4 changes the cart.

A getter on the prototype uses the object you read fromPop out in the code editor (opens in a new tab)JavaScript
const shared = {  get label() { return this.name; },};const user = Object.create(shared);user.name = "Asha";console.log(user.label);

A getter is a method that runs when you read a property. It is written with the word get. Lines 1 to 3 put a getter named label on shared. It returns this.name.

Line 4 makes user with shared as its prototype. Line 5 sets user.name to "Asha". Line 6 reads user.label and prints Asha.

The getter lives on shared, but this is user. That is the receiver from the OrdinaryGet steps: the object the read started from. It is passed along unchanged when the read moves to the prototype.

The ? and ! shorthands

Every spec step finishes in one of two ways. It finishes normally with a result. Or it finishes abruptly, for example by throwing an error. The spec calls this outcome a completion. The next lesson looks at completions in detail.

A ? in front of a step means: "If this step throws, stop here and pass the error back to whoever asked. If it works, use its result and go on."

An object key that turns into textPop out in the code editor (opens in a new tab)JavaScript
const key = { toString: () => "tea" };const cart = { tea: 3 };console.log(cart[key]);

Line 1 makes a key object. Its toString method returns the text "tea". Line 2 makes a cart with tea: 3. Line 3 reads cart[key].

The key turns into the text "tea" without any error, so the read prints 3. Every step here finished normally.

Here is a ? in a real rule, ToIntegerOrInfinity. This rule turns a value into a whole number.

How ToIntegerOrInfinity starts, from the specText
ToIntegerOrInfinity ( arg )
1. Let number be ? ToNumber(arg).
2. If number is one of NaN, +0, or -0, return 0.

In plain words, line by line:

  1. The rule is called ToIntegerOrInfinity. Its input is named arg.
  2. Turn arg into a number and call it number. The ? means: if that throws, stop and hand the error back.
  3. If number is NaN, +0, or -0, hand back 0.

The spec has a name for what ? does: ReturnIfAbrupt. It means "if this step ended abruptly, return that right away".

The step ? ToNumber(arg) has two ways out. If it works, go on to step 2 with the number. If it throws an error, stop and hand the error back.? ToNumber(arg)works: go to step 2throws: hand it back
The ? in step 1 gives two ways out. If ToNumber works, go on to step 2. If it throws, stop here and hand the error back.
An error skips the rest of the try blockPop out in the code editor (opens in a new tab)JavaScript
const price = {  [Symbol.toPrimitive]() { throw new Error("bad price"); },};try {  console.log(Number(price));  console.log("after");} catch (error) {  console.log(error.message);}

Lines 1 to 3 make a price object. Its [Symbol.toPrimitive] method throws an error, "bad price". Line 5 asks Number(price) for a number, so the method runs and throws.

Line 6 never runs, so after is never printed. JavaScript jumps to the catch block, and line 8 prints bad price.

This is the same "stop early" idea as ?. You can see the result, but you can't see the completion itself from JavaScript.

A ! in front of a step means: "This step can't fail here, so just take its result." Look at step 3 of ToPropertyKey: ! ToString(key). By then, key is a primitive and not a Symbol. For a primitive, ToString only throws for a Symbol, so it can't throw here.

In the spec, ! does not mean "not", as it does in JavaScript. It also doesn't mean "ignore the error".

A number key that converts with no errorPop out in the code editor (opens in a new tab)JavaScript
const cart = { 3: "tea" };console.log(cart[3]);

Line 1 stores "tea" under the key 3. Line 2 reads with the number 3 and prints tea. Turning 3 into the text "3" can't fail. That is the spot where the spec writes !.

The ! lives only in the spec's steps. You never type it in front of cart[3].

Rules that follow the shape of the code

Some rules work on your code as written, before it runs. The spec calls them syntax-directed operations. First the engine reads your code and splits it into pieces. Each piece is called a parse node. Each piece matches a grammar pattern, such as "a name". The spec gives steps for each pattern.

Take an identifier: a name you write in code, such as a variable name. The rule StringValue gives the name as written. Running the code asks a different question: what value is stored under that name right now?

One written name, one valuePop out in the code editor (opens in a new tab)JavaScript
const price = 3;console.log(price);

Line 1 makes a variable written as price and stores 3 in it. Line 2 reads the variable and prints 3. The name price comes from the code as you wrote it. The value 3 comes from running the code.

Left: StringValue gives the written name, price, shown as a tag. Right: running the code gives the value 3, shown as a card in a box called price.StringValuepricethe written nameEvaluation3pricethe value now
StringValue reads the name as written in the code: price. Running the code reads what is stored under that name: 3.

The box below comes from Identifiers: Static Semantics: StringValue. It is spec text, not a declaration you can run.

How StringValue works for a name, from the specText
Static Semantics: StringValue
Identifier : IdentifierName but not ReservedWord
1. Return the StringValue of IdentifierName.

In plain words, line by line:

  1. This is the StringValue rule. "Static Semantics" means it looks at code without running it.
  2. This version is for an Identifier: a name that is not a reserved word. Reserved words are words JavaScript keeps for itself, such as if and const.
  3. Hand back the text of the name, exactly as written.
A name is not the value it holdsPop out in the code editor (opens in a new tab)JavaScript
const price = 3;let total = price + 2;console.log(total);

Line 1 stores 3 in price. Line 2 adds 2 and stores 5 in total. Line 3 prints 5.

price and total are names written in the code. The 5 is only worked out when the code runs. It is not written anywhere in the code.

Real-life analogyA school attendance register

A school register is a list of students. Each line has a student's name and a mark beside it, such as "present". Reading the name is not the same as reading the mark.

In real life: A student's name is written in the register
In JavaScript: A variable's name is written in the code
In real life: A mark is written beside the name
In JavaScript: The variable holds a value right now
In real life: The teacher reads the mark
In JavaScript: Running the code reads the value

The spec also has rules headed Runtime Semantics: Evaluation. They say what happens when a piece of code runs. So the heading tells you which kind of rule you are reading: one that looks at the code, or one that runs it.

This matters for errors. A syntax error is found while the code is being read. So it stops the program before even the first console.log runs.

Trace a real app question

Say a checkout page reads a field from a cart, and a form chooses which field. To explain what it prints, you need two answers:

  • Which key did the form choose?
  • Which object holds the value for that key?

You don't need to look inside the engine. Start with a tiny version of the code.

Read a cart field chosen by a variablePop out in the code editor (opens in a new tab)JavaScript
const cart = { tea: 3 };const key = "tea";console.log(cart[key]);

Line 1 puts 3 under tea. Line 2 sets key to the text "tea". Line 3 reads cart[key] and prints 3. The key is already text, so ToPropertyKey hands it back unchanged.

What if the form gave an object instead of text? Then follow these rules in order:

  • First, ToPropertyKey: which key does the object turn into?
  • Then, [[Get]]: is the property on the object itself, on its prototype, or is it a getter?

A Proxy can show you which key was used. A Proxy's trap is a method that runs when you use the Proxy, such as get for a read. The trap is your own code. It is not a window into the engine.

Use a Proxy to print each key that is readPop out in the code editor (opens in a new tab)JavaScript
const cart = new Proxy({ tea: 3 }, {  get(target, key, receiver) {    console.log(String(key));    return Reflect.get(target, key, receiver);  },});console.log(cart.tea);

Line 1 wraps a { tea: 3 } object in a Proxy. Line 2 adds a get trap. When line 7 reads cart.tea, line 3 prints the key, tea.

Line 4 uses Reflect.get, a built-in function that does the normal read, and returns its result. Line 7 prints that result, 3. So the output is two lines: tea, then 3.

The spec uses a few kinds of notation that look alike. Read each row as: "when you see this, it is this kind of thing, and it means this."

Spec notation that looks alike but does different jobs
When you seeWhat kind of thing it isWhat it means
ToPropertyKey(value)A named spec rule (an abstract operation)Steps written in the spec. You can't call it from JavaScript.
object.[[Get]](key, receiver)A hidden behaviour (an internal method)The steps for reading a property. Some objects, such as a Proxy, have their own.
object.[[Prototype]]Hidden data (an internal slot)The object's prototype link. It is not a property named [[Prototype]].
? operation()A spec markIf the step throws, stop and pass the error on. If not, use its result.
! operation()A spec markThis step can't fail here, so just use its result.
Code you can run, or spec notation?
  • cart[3]
  • String(3)
  • ToPropertyKey(3)
  • OrdinaryGet(cart, key, receiver)
  • cart.[[Prototype]]
  • cart.[[Get]](key, receiver)
Try it yourself
0 of 6 correct

Put each card in the right group. Then read why it belongs there.

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

Common misconceptions

The spec says what the result must be. It does not say what code or memory layout an engine must use. The step-throughs in this lesson help you learn the steps, but they don't show what an engine really does inside. Keep what your code prints apart from these teaching models.

  • “I can call ToPropertyKey in JavaScript.” It is a spec rule, not a function your code can call.
  • “A property named [[Prototype]] is the internal slot.” Putting brackets in a text name only makes a normal property.
  • “Spec ! means JavaScript 'not'.” In spec steps, ! means "this step can't fail here".
  • “Spec ? is like the ? : choice in JavaScript.” In spec steps, ? means "if this step throws, stop and pass the error on".
  • “All [[Get]] methods are the same.” Special objects, such as a Proxy, can have their own [[Get]] steps.

Always read a mark where it appears. In JavaScript, !price means "not price". In a spec step, ! ToString(key) means "this can't fail here".

In the same way, a normal property with brackets in its name does not become a hidden slot just because it looks like one.

Read each row of the table as: "in the spec, this means that, and it is not the same as this other thing."

Four spec ideas that are easy to mix up
When you seeWhat it means in the specNot the same as
! before a spec stepThis step can't fail here, so use its result.JavaScript's !, which means "not".
? before a spec stepIf this step throws, stop and pass the error on.JavaScript's ? :, which chooses between two values.
[[Prototype]]Hidden data that holds an object's prototype.The normal .prototype property that functions have.
StringValueA rule that gives a name as it is written in the code.Calling String(...) on a value while the code runs.

Practice exercises

Start by predicting what each program prints. Then name the spec rule that explains it. You can run each program in the editor and compare it with your guess before you read the solution.

Exercise 1 · Warm-upPredict two key reads

The cart stores tea under the key 3. Predict the two values printed on one console line. Explain why they are the same.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const cart = { 3: "tea" };
console.log(cart[3], cart["3"]);

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

    Exercise 2 · Warm-upFind the conversion rule

    Look again at the cart from exercise 1. Name the abstract operation that turns the value in square brackets into a property key. Don't type a JavaScript function name: this rule exists only in the spec.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const cart = { 3: "tea" };
    console.log(cart[3], cart["3"]);

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

      Exercise 3 · PracticeFollow a read to the prototype

      Here cart has no tea of its own. What does the code print? Which object holds that value?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const shared = { tea: 3 };
      const cart = Object.create(shared);
      console.log(cart.tea);

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

        Exercise 4 · PracticeSpot the skipped line

        The object refuses to turn into a number. Predict what this try/catch prints. Explain why the line that prints after is skipped.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        try {
          Number({ [Symbol.toPrimitive]() { throw new Error("bad price"); } });
          console.log("after");
        } catch (error) {
          console.log(error.message);
        }

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

          Exercise 5 · ChallengeName the kind of rule

          The code writes the name price and prints its value. Which kind of spec rule gives the written name? Keep it apart from running the code, which reads the value.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const price = 3;
          console.log(price);

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

            Exercise 6 · ChallengeApply it to a checkout page

            Your checkout page reads cart[field], but sometimes the form sends the wrong field. Which rule tells you how field becomes a property key? Run the starter code first to see the normal case.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const cart = { tea: 3 };
            const field = "tea";
            console.log(cart[field]);

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

              Check your understanding

              For code questions, guess the output before you look at the choices. For notation questions, ask: is this code I can run, a named spec rule, or a hidden part of an object?

              Reading ECMAScript quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Where would you look for the rule that turns a value into a property key?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this code print when it reads the key 3 in two ways?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const cart = { 3: "tea" };
                console.log(cart[3], cart["3"]);

                Choose an answer to see the explanation.

              3. Question 3 of 8Which part of [[Get]] can your code read as a normal property?

                Choose an answer to see the explanation.

              4. Question 4 of 8What does this code print when cart has no tea of its own?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const shared = { tea: 3 };
                const cart = Object.create(shared);
                console.log(cart.tea);

                Choose an answer to see the explanation.

              5. Question 5 of 8What does ? ToNumber(arg) mean in a spec step?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does ! ToString(key) mean in ToPropertyKey?

                Choose an answer to see the explanation.

              7. Question 7 of 8What does this code print when an object is used as the key?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const key = { toString: () => "tea" };
                const cart = { tea: 3 };
                console.log(cart[key]);

                Choose an answer to see the explanation.

              8. Question 8 of 8What does a syntax-directed operation work on?

                Choose an answer to see the explanation.

              Key takeaways

              The spec is easier to read when you start with one small result you can see. Find the rule for that code, follow the named rules it uses, and stop once the steps explain the output.

              • Grammar patterns describe how code is written. Static Semantics rules look at the code; Runtime Semantics rules say what happens when it runs.
              • Abstract operations, such as ToPropertyKey and Call, are named spec rules. You can't call them from JavaScript.
              • Internal slots are hidden data, and internal methods are hidden behaviours. Both use double square brackets in the spec.
              • A ? before a step means "if it throws, stop and pass the error on". A ! means "this step can't fail here".
              • Syntax-directed operations, such as StringValue, give steps for each grammar pattern, such as a name.

              Remember the one-liner.
              Read one JavaScript result, find its rule, then follow only the steps needed to explain it.

              Coming next: Spec types: Completion, Property Descriptor & more. That lesson looks closer at the records behind these rules, including the completions that ? passes on.

              CompleteFrontend Clear concepts. Working examples.