completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

A tour of the abstract operations

Follow JavaScript's named specification rules for converting objects, comparing values, stepping through iterators, and choosing array results.

By the end, you can
  • 01
    Follow a conversionSay which method runs first when an object becomes a primitive, a property name, or a number.
  • 02
    Explain comparisonsTell when == converts a value, and show that < and > always convert the left value first.
  • 03
    Read loops and new arraysExplain what next() returns, why break calls return(), and how map picks the class for a new array.

One rule used in many places

The rules of JavaScript are written in a long document called the specification, or spec. The lesson How to read ECMAScript showed that the spec is full of named rules. In this lesson you follow some of those rules through code you can run.

An abstract operation is one of these named rules. The spec uses the same rule in many places. It is not a function in your program, so your code can't call it.

Add 2 to an objectPop out in the code editor (opens in a new tab)JavaScript
const price = { valueOf() { return 3; } };
console.log(price + 2);

Line 1 makes a price object. It has a valueOf method that returns 3. A method is a function stored on an object. Line 2 adds 2 to the object and prints 5.

How can you add a number to an object? Before adding, JavaScript asks the object for a plain value. A plain value is called a primitive. It is any value that is not an object, such as a number, a string, or a BigInt. A BigInt is a whole number written with an n at the end, like 3n.

price + 2. The price object holds a valueOf method. It gives the number 3. Then 3 plus 2 gives 5.price + 2valueOf()price3a number+ 25the sum
Addition can't add an object. So it calls valueOf() on price, gets the number 3, and then adds 2 to make 5.
The main idea

An abstract operation is a named rule in the spec. It describes one job the language must do, such as "turn this object into a primitive". The spec reuses the rule wherever that job comes up. To explain a surprising result, start from your code and follow only the rules it needs.

The lesson before this one, Internal methods & exotic objects, showed how objects answer when you read a property. This lesson asks what happens when you use an object in other ways:

  • as a property name, also called a key
  • as a number
  • in a comparison, like < or ==
  • in a loop that takes values one at a time
  • when an array method makes a new array

The spec says what result your code will see. It does not say how the engine does the work inside.

How an object becomes a primitive

ToPrimitive is the abstract operation that turns an object into a primitive. It takes a hint: a word that says which kind of result is wanted, such as "number" or "string". The hint only decides which method is tried first. It does not force the type of the result.

Most objects have no special conversion method of their own. (You'll meet one in the next section.) Then ToPrimitive hands the job to a second rule, OrdinaryToPrimitive. That rule tries the object's valueOf and toString methods, one after the other.

valueOf gives the number 3Pop out in the code editor (opens in a new tab)JavaScript
const price = { valueOf() { return 3; } };
console.log(price + 2);

Line 1 gives the object a valueOf method that returns the number 3. Line 2 prints 5. For a plain object like this, + tries valueOf first. It gets 3, so it adds two numbers: 3 + 2. The spec's ToPrimitive steps show every case.

If valueOf gives back an object, toString is tried nextPop out in the code editor (opens in a new tab)JavaScript
const calls = [];
const price = {
  valueOf() { calls.push("valueOf"); return {}; },
  toString() { calls.push("toString"); return "3"; }
};
console.log(Number(price), calls.join(","));

Each method in this example writes its own name into a list, so you can see which methods ran. Line by line:

  1. Line 1 makes an empty list called calls.
  2. Line 3: valueOf writes its name, then returns an empty object, {}. An object is not a primitive, so it doesn't count.
  3. Line 4: toString writes its name and returns the string "3". That is a primitive, so the search stops here.
  4. Line 6: Number(price) turns the string "3" into the number 3. It prints 3 valueOf,toString.

If both methods return objects, OrdinaryToPrimitive gives up and throws a TypeError. It never accepts an object as the final answer.

Real-life analogyCalling a friend from your contacts

To call a friend, your phone needs a number it can dial, not the whole contact card. It looks at the card for a mobile number first. If there is none, it looks for a home number. It dials the first number it finds.

In real life: The whole contact card
In JavaScript: The object
In real life: A number you can dial
In JavaScript: A primitive
In real life: Check the mobile number, then the home number
In JavaScript: Try valueOf, then toString
In real life: Dial the first number you find
In JavaScript: Use the first primitive that comes back

The hint decides which method goes first

The hint changes the order of the two methods:

  • With a "number" hint, OrdinaryToPrimitive tries valueOf first, then toString.
  • With a "string" hint, it tries toString first, then valueOf.

The second method runs only if the first one gives back an object. String(key) asks for a string, so it uses the string hint.

String() tries toString firstPop out in the code editor (opens in a new tab)JavaScript
const calls = [];
const key = {
  valueOf() { calls.push("valueOf"); return 3; },
  toString() { calls.push("toString"); return "tea"; }
};
console.log(String(key), calls.join(","));

Line 1 makes the list. Line 3 has a valueOf that could return 3. But String(key) asks for a string, so line 4's toString runs first. It returns "tea", which is already a primitive. Line 6 prints tea toString. valueOf never ran.

Left: Number(price) tries valueOf first, then toString. Right: String(key) tries toString first, then valueOf.Number(price)1stvalueOf()2ndtoString()String(key)1sttoString()2ndvalueOf()
Number(price) wants a number, so it tries valueOf() first. String(key) wants a string, so it tries toString() first.

An object can also take over conversion completely. It does this with a method named Symbol.toPrimitive. A Symbol is a special kind of value that can be used as a property name. Symbol.toPrimitive is a built-in Symbol that JavaScript knows to look for. In this lesson we call that method the conversion hook. ToPrimitive checks for the hook before anything else, and passes it the hint as a string.

The conversion hook receives the hintPop out in the code editor (opens in a new tab)JavaScript
const price = {
  [Symbol.toPrimitive](hint) {
    console.log(hint);
    return 3;
  }
};
console.log(price + 2);
console.log(Number(price));

Line by line:

  1. Lines 2 to 5 define the hook. Line 3 prints the hint it gets. Line 4 returns 3.
  2. Line 7: + doesn't prefer a type, so the hint is "default". It prints default, then 5.
  3. Line 8: Number(price) wants a number, so the hint is "number". It prints number, then 3.

The hook runs before OrdinaryToPrimitive. If the hook returns an object, JavaScript throws a TypeError. It does not try valueOf after that.

Step through turning an object into a number
Step 0 of 7Ready
Your turn: follow the blue line

A replay of the example code, one step at a time. It is not an engine debugger, so it doesn't show what happens inside the engine.

Running in
  1. script
Next: line 4
function total(price) {  return price + 2;}  [Symbol.toPrimitive](hint) {    console.log(hint);    return 3;  }};console.log(total(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.

Press Step to walk through a replay of a small total function. You'll see the hook get the hint default and return 3. Then addition returns 5. The replay runs the example code step by step; it doesn't show what happens inside the JavaScript engine. Stepping like this helps you find which part of a surprising line runs extra code.

How a value becomes a property name

A property name is called a key. Every key on an object is either a string or a Symbol. ToPropertyKey is the abstract operation that turns any value into a key. It works in two steps:

  1. It calls ToPrimitive with the string hint.
  2. If the result is a Symbol, it keeps it. Anything else becomes a string.

So a number in square brackets, like cart[3], finds a property stored under the string "3".

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

Line 1 stores "tea" under the key 3. Keys are always strings or Symbols, so the key is really "3". Line 2 reads it twice: once with the number 3, and once with the string "3". It prints tea tea. A plain object never has a separate key that is a number.

cart[3]. The number 3 becomes the string 3. The cart holds the key string 3 with the value tea.cart[3]3number"3"string"3": "tea"cart
A property name is always a string or a Symbol. So the number 3 becomes the string "3" first, and cart[3] finds "tea".
An object used as a key gets the string hintPop 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"]);

Square brackets can hold any value, even an object. A key written in square brackets is called a computed key. Line by line:

  1. Line 1 makes an empty cart.
  2. Lines 2 to 7 make a key object. Its conversion hook prints the hint and returns the number 3.
  3. Line 8 uses the object as a key. The hook prints string. The number 3 then becomes the string "3", and "tea" is stored there.
  4. Line 9 reads cart["3"] and prints tea.

The spec's ToPropertyKey steps list these two steps.

A Symbol key is not the same as its name in a stringPop out in the code editor (opens in a new tab)JavaScript
const key = Symbol("tea");
const cart = { [key]: 3 };
console.log(cart[key], cart["Symbol(tea)"]);

Line 1 makes a Symbol. The text "tea" is its description: a label for people reading the code. Line 2 stores 3 under the Symbol. Line 3 prints 3 undefined.

Reading with the Symbol finds 3. Reading with the string "Symbol(tea)" finds nothing, because that string is a different key. The description only helps you tell Symbols apart. It can't stand in for the Symbol.

A BigInt stays a BigInt in math

ToNumeric is the abstract operation that math operators such as ++ and - use to get a number. It works in two steps:

  1. It calls ToPrimitive with the number hint.
  2. If the result is a BigInt, it returns it unchanged. Anything else goes through ToNumber, which makes a normal number.

So a BigInt stays a BigInt. It is never quietly changed into a normal number, which could lose digits of a very large value.

Add one to an object that gives a BigIntPop out in the code editor (opens in a new tab)JavaScript
let price = { valueOf() { return 3n; } };
console.log(typeof ++price, price === 4n);

Line 1 makes an object whose valueOf returns 3n. Line 2 runs ++price. The ++ operator adds one and saves the new value back into price. ToNumeric gets 3n, so the new value is 4n.

typeof gives the type of a value as a string. So line 2 prints bigint true. The spec's ToNumeric steps show the BigInt case.

< can mix BigInt and number, but + can'tPop out in the code editor (opens in a new tab)JavaScript
console.log(3n < 4);
try { console.log(3n + 4); }
catch (error) { console.log(error.name); }

Line 1 prints true. The < operator can compare a BigInt with a normal number. Line 2 tries to add 3n and 4. That throws a TypeError. Line 3 catches the error and prints its name, TypeError.

So ToNumeric keeps a BigInt safe, but each operator still has its own rules about mixing a BigInt with a normal number.

Change the price limit
The code you are changingPop out in the code editor (opens in a new tab)JavaScript
function comparePrice(input) {  const price = { valueOf() { return 3; } };  return price < input;}console.log(comparePrice(4));
Result
true
Try it yourself

The object gives 3. Is 3 < 4? The answer is true. Reset sets the limit back to 4.

This runs the same comparePrice function as the example code. It doesn't show what happens inside the engine.

Move the slider to change only the limit. The function turns an object into 3, then checks whether 3 is less than your limit. Reset sets the limit back to 4, which gives true. This runs the real JavaScript comparison.

== and < follow different rules

IsLooselyEqual is the abstract operation behind ==, which is called loose equality. It looks at the types of the two values and picks a matching case. Two of its cases:

  • A number and a string: the string is turned into a number.
  • An object and a number or string: the object is turned into a primitive.

=== is called strict equality. It follows a different rule, IsStrictlyEqual, which never converts. Two values of different types are never strictly equal.

== converts the string, === does notPop out in the code editor (opens in a new tab)JavaScript
console.log("3" == 3);
console.log("3" === 3);

Line 1 turns "3" into the number 3 and prints true. Line 2 uses === and prints false, because a string and a number are different types. For a full introduction to these operators, see Equality & sameness.

== doesn't always convert an objectPop out in the code editor (opens in a new tab)JavaScript
const price = { valueOf() { console.log("valueOf"); return 3; } };
console.log(price == 3);
console.log(price == null);

Line by line:

  1. Line 1 gives price a valueOf method. It prints valueOf and returns 3.
  2. Line 2 compares price with 3. That case turns the object into a primitive, so it prints valueOf, then true.
  3. Line 3 compares price with null. No case converts here, so valueOf doesn't run. It just prints false.

null is only loosely equal to null and undefined. Browsers also have one old special object, document.all, with its own case. It isn't part of this example.

IsLessThan is the abstract operation behind <, >, <=, and >=. First it turns both values into primitives. Then:

  • If both are strings, it compares them character by character. Each character has a number code, and the codes are compared in order, a bit like words in a dictionary.
  • Otherwise it compares them as numbers. BigInts and strings have a few special cases.

Some values can't be put in order, such as NaN ("not a number"). For those, IsLessThan gives undefined inside the spec. The operators then turn that into false.

Two strings compare like words, not numbersPop out in the code editor (opens in a new tab)JavaScript
console.log("10" < "2");
console.log("10" < 2);

Line 1 prints true. Both values are strings, so the first characters are compared, and "1" comes before "2". Line 2 prints false. One value is a number, so both are compared as numbers, and 10 is not less than 2. So don't sort prices stored as strings with <.

The left value is always converted firstPop out in the code editor (opens in a new tab)JavaScript
const left = { valueOf() { console.log("left"); return 3; } };
const right = { valueOf() { console.log("right"); return 4; } };
console.log(left < right);
console.log(left > right);

Line by line:

  1. Lines 1 and 2 make two objects. Each one prints its name when it is converted.
  2. Line 3 prints left, right, then true.
  3. Line 4 prints left, right, then false.

Inside the spec, left > right is checked as "is right less than left?" That swaps the two values. So IsLessThan takes one more yes-or-no input, called LeftFirst. It says which value to convert first. That way the value on the left in your code is always converted first.

NaN can't be put in orderPop out in the code editor (opens in a new tab)JavaScript
console.log(NaN < 3, NaN >= 3);

Line 1 prints false false. NaN is not less than 3, and it is not greater than or equal to 3 either. IsLessThan gives undefined for NaN, and both operators turn that into false.

If a real input behaves differently from these small examples, read the full cases in IsLooselyEqual and IsLessThan.

The table below compares the three rules. Read each row as: "this rule runs for this operator, and this is what it does."

Three comparison rules and what they do
RuleWhich operator uses itWhat it does
IsLooselyEqual==Looks at the two types. In some cases it converts one value, for example an object compared with a number.
IsStrictlyEqual===Never converts. Two values of different types are never equal.
IsLessThan<, and also >, <=, >=Turns both values into primitives, always the left value first.

How a loop takes values one at a time

An iterable is a value you can loop over with for...of, like an array. It has a method named Symbol.iterator. That method returns an iterator: an object with a next() method that hands out values one at a time.

Each call to next() returns a small result object with two properties:

  • value: the next value.
  • done: true when there are no more values.

GetIterator is the abstract operation that calls Symbol.iterator to get the iterator. It keeps three things together: the iterator, its next method, and whether it has finished. That bundle is called an Iterator Record. It exists only inside the spec.

An array can be looped overPop out in the code editor (opens in a new tab)JavaScript
const items = ["tea", "milk"];
for (const item of items) console.log(item);

Line 1 makes an array with "tea" and "milk". Line 2 loops over it with for...of and prints tea, then milk. Each time round, the loop asks for the next result. It stops when done is true.

Watch next() and return() during a loopPop out in the code editor (opens in a new tab)JavaScript
const items = {
  [Symbol.iterator]() {
    console.log("iterator");
    let index = 0;
    return {
      next() {
        console.log("next");
        return index++ === 0 ? { value: "tea", done: false } : { done: true };
      },
      return() { console.log("return"); return { done: true }; }
    };
  }
};
for (const item of items) { console.log(item); break; }

This iterable prints a word each time one of its methods runs. Line by line:

  1. Line 2 defines the Symbol.iterator method. Line 3 prints iterator when the loop starts.
  2. Lines 6 to 9 define next(). Line 7 prints next. On the first call, line 8 returns a result with the value "tea" and done: false.
  3. Line 10 defines return(). JavaScript calls it when a loop stops early, so the iterator can clean up.
  4. Line 14 prints tea, then break stops the loop. That calls return(), which prints return.

So the output is iterator, next, tea, return.

Two abstract operations do the asking:

  • IteratorStep calls next() and checks done. It returns the whole result object, or a spec marker called DONE when the iterator has finished. It does not read value.
  • IteratorStepValue does the same, and then reads value if the iterator hasn't finished.

These are two separate operations in the current spec. Also, a loop that reads every value to the end doesn't need to call return(). Only an early stop does.

Reading to the end doesn't call return()Pop out in the code editor (opens in a new tab)JavaScript
const items = {
  [Symbol.iterator]() {
    let count = 0;
    return {
      next() { console.log("next"); return count++ ? { done: true } : { value: "tea", done: false }; },
      return() { console.log("return"); return { done: true }; }
    };
  }
};
console.log([...items].join(","));

Line 1 makes an iterable. Line 5's next() prints next each time it runs. Line 6 defines a return() method. Line 10 uses spread, [...items], which copies every value into a new array.

It prints next, next, then tea. The spread read all the way to the end, so return() never ran.

Two consoles. Left, the loop stops early with break: it prints iterator, next, tea, return. Right, the spread reads every value: it prints next, next, tea, and return never runs.Stop early with breakConsoleiteratornextteareturnRead every valueConsolenextnextteano return
Left: the loop stops early with break, so return() runs to close the iterator. Right: the spread reads to the end, so return() never runs.
When done is true, value is never readPop out in the code editor (opens in a new tab)JavaScript
const items = {
  [Symbol.iterator]() {
    return { next() { return { get done() { console.log("done"); return true; }, get value() { console.log("value"); return "tea"; } }; } };
  }
};
console.log([...items].length);

Line 3 returns a result object with two getters. A getter is a property that runs a function when you read it. Here each getter prints its own name. Line 6 spreads the iterable and prints 0, because there were no values.

The only other output is done. Once done is true, value is never read. This shows the two steps: first check done, then read value only if there is one.

Step through a loop that stops early
Step 0 of 8Ready
Your turn: follow the blue line

A replay of the loop example, one step at a time. It is not an engine debugger, so it doesn't show what happens inside the engine.

Running in
  1. script
Next: line 7
function first(items) {  for (const item of items) {    console.log(item);    break;  }}  [Symbol.iterator]() {    console.log("iterator");    return {      next() { console.log("next"); return { value: "tea", done: false }; },      return() { console.log("return"); return { done: true }; }    };  }};first(items);
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 a replay of the first function with a real iterable. You'll see the loop get the iterator, call next(), put "tea" in item, and call return() after break. The replay runs the example code step by step; it doesn't show what happens inside the JavaScript engine.

The table below lists the four iterator rules. Read each row as: "this rule does this, and gives back this."

The four iterator rules
RuleWhat it doesWhat it gives back
GetIteratorCalls the Symbol.iterator method to get the iteratorThe iterator and its next method, kept together inside the spec
IteratorStepCalls next() and checks doneThe whole result object, or DONE when finished
IteratorStepValueDoes the same, then reads value if not finishedThe value, or DONE when finished
IteratorCloseCalls return() when a loop stops earlyNothing your loop uses. A loop that reads to the end skips this rule.

Which class a new array gets

Some array methods, like map and slice, make a new array. If you made your own kind of array, which kind should the new one be? First, two words you need:

  • A class is a template for making objects. class Orders extends Array makes a new kind of array called a subclass.
  • A constructor is the function that builds a new object, like Array or Orders.

SpeciesConstructor is the spec rule that picks the constructor for a new, related object. It reads the object's constructor, then that constructor's Symbol.species property. Array methods like map use their own array version of the same idea. Not every method or copy uses species.

map on a subclass gives the same subclassPop out in the code editor (opens in a new tab)JavaScript
class Orders extends Array {}
const orders = new Orders("tea", "milk");
console.log(orders.map(item => item.toUpperCase()) instanceof Orders);

Line 1 makes Orders, a subclass of Array. Line 2 makes an Orders list. Line 3 maps it to a new list. instanceof checks whether a value was made by a class. It prints true: by default, the species of Orders is Orders itself.

Species can make map return a plain arrayPop out in the code editor (opens in a new tab)JavaScript
class Orders extends Array {
  static get [Symbol.species]() {
    console.log("species");
    return Array;
  }
}
const orders = new Orders("tea", "milk");
const copy = orders.map(item => item.toUpperCase());
console.log(copy instanceof Orders, copy instanceof Array, copy.join(","));

Line by line:

  1. Lines 2 to 5 define a static getter for Symbol.species. static means it belongs to the class itself, not to each list. It prints species and returns Array.
  2. Line 7 makes an Orders list.
  3. Line 8 maps it. map reads the species, so species is printed.
  4. Line 9 prints false true TEA,MILK. The new list, copy, is a plain Array, not an Orders.

Species only changes the new array. The original orders is still an Orders.

A null species means: use a plain ArrayPop out in the code editor (opens in a new tab)JavaScript
class Orders extends Array {
  static get [Symbol.species]() { return null; }
}
const orders = new Orders("tea");
console.log(orders.slice() instanceof Orders);

Line 2 makes the species null. Line 4 makes an Orders list. Line 5 copies it with slice() and prints false: the copy is a plain Array.

In the SpeciesConstructor rule, a species of undefined or null means "use the default constructor". A species that is not a constructor makes JavaScript throw.

A species that can't build arrays throwsPop out in the code editor (opens in a new tab)JavaScript
class Orders extends Array {
  static get [Symbol.species]() { return 3; }
}
try { new Orders("tea").map(item => item); }
catch (error) { console.log(error.name); }

Line 2 sets the species to the number 3, which can't build anything. Line 4 asks map for a new array. That throws a TypeError. Line 5 catches it and prints TypeError.

In your own code, if you want a plain array, it's clearer to make one directly, for example with Array.from(orders). Species exists mainly so older code keeps working. It is not a general way to change how objects are made.

Trace a checkout bug

Say a checkout page gets a form field as an object, not as a string. The page uses that object as a key to find an item in the cart. A string key is easy to check. But an object key can run your own code while it is being converted. So before you blame the framework or the browser, cut the problem down to a cart and one field.

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

Line 1 makes a cart with tea at price 3. Line 2 makes a field object whose toString returns "tea". Line 3 prints 3.

ToPropertyKey asks the object for a primitive with the string hint. It gets "tea", so cart[field] reads cart.tea. You see the result, but you never call ToPropertyKey yourself. It's a rule in the spec, not a function.

Stop after the first cart itemPop out in the code editor (opens in a new tab)JavaScript
const cart = ["tea", "milk"];
for (const item of cart) {
  if (item === "tea") { console.log(item); break; }
}

Line 1 makes a cart array. Line 2 starts the loop. Line 3 prints tea and stops right away with break, so milk is never printed.

If your real cart is your own iterable, test its next() and return() methods. Then you'll know what clean-up happens when a loop stops early.

For more conversion examples, see Type coercion. For more about comparisons, see Equality & sameness. This lesson has a smaller goal: find the one named rule that explains a surprising step, then check it with a tiny program.

Which kind of rule explains it?
  • An object is used in price + 2
  • An object is used as a property name
  • Check "3" == 3
  • Check "10" < "2"
  • A loop calls Symbol.iterator
  • A loop calls next() and checks done
Try it yourself
0 of 6 correct

Sort each situation into the kind of rule it uses: conversion, comparison, or iteration. Then read why.

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

Common mistakes

The name of a spec rule helps you explain what happens. It is not a JavaScript function you can call. It also doesn't mean the engine has a function with that name inside. Always ask: what result can my code see?

== converts the object, === does notPop out in the code editor (opens in a new tab)JavaScript
const price = { valueOf() { return 3; } };
console.log(price == 3, price === 3);

Line 1 makes an object that gives 3 when converted. Line 2 prints true false. == converts the object, because the other value is a number. === never converts, and an object is not a number. So == doesn't convert everything. It converts only in certain cases.

Here are five common mistakes, each with what really happens:

  • "The hint decides the type of the result." It only decides which method is tried first. A conversion hook can return any kind of primitive.
  • "== always converts both values." Two values of the same type are compared without converting. An object compared with null doesn't call valueOf.
  • "> converts the right value first." The left value in your code is always converted first. The LeftFirst input makes sure of that.
  • "IteratorStep gives you the value." It gives the whole result object, or DONE. IteratorStepValue is the one that reads value.
  • "Species changes the original array." It only changes the class of some new arrays.

A loop that reads to the end and a loop that stops early with break also end differently. An iterator doesn't have to have a return() method. If it has one, JavaScript calls it when a loop stops early. This matters when an iterable holds something that must be closed, like an open file.

The table below compares the three conversion rules. Read each row as: "this rule turns a value into this, and it starts like this."

Three conversion rules compared
RuleWhat it turns a value intoHow it starts
ToPrimitiveA primitive (any value that is not an object)Checks for a conversion hook. If there is none, the hint picks whether valueOf or toString goes first.
ToPropertyKeyA key: a string or a SymbolCalls ToPrimitive with the string hint
ToNumericA normal number or a BigIntCalls ToPrimitive with the number hint

Practice exercises

Guess the output before you run the starter code. Each exercise asks what the code prints. Once you know the output, name the rule that explains it.

Exercise 1 · Warm-upWhat does price + 2 print?

A receipt keeps its price in an object with a valueOf method. Read the code and type the number it prints. Which method gave the first number?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const price = { valueOf() { return 3; } };
console.log(price + 2);

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

    Exercise 2 · Warm-upFind the cart key

    The cart stores tea under the key "3". The code reads it with the number 3. Type the one word it prints. What key does ToPropertyKey make from 3?

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

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

      Exercise 3 · PracticeCompare without guessing

      A form gives you the text "3", and a price is stored as the number 3. Type both true-or-false values it prints. Could you swap these two operators in checkout code and get the same results?

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

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

        Exercise 4 · PracticeStop a shopping-list loop

        The app looks through a shopping list and stops at the first item. What word is printed? Why is the second item never printed?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const items = ["tea", "milk"];
        for (const item of items) { console.log(item); break; }

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

          Exercise 5 · ChallengeWhat kind of array does map make?

          Your app has an Orders subclass of Array, but map should return a plain array. The subclass has a species getter. Is the new array an Orders? Type true or false.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          class Orders extends Array { static get [Symbol.species]() { return Array; } }
          console.log(new Orders("tea").map(item => item) instanceof Orders);

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

            Exercise 6 · ChallengeUse conversion on a real site

            A checkout form gives you an object instead of a string, and the cart shows the wrong item. This small example does the same lookup. Guess what it prints before you debug the whole page.

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

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

              Check your understanding

              Each question has one right answer. For code questions, find the exact output. For the other questions, first name the rule that does the work, then choose.

              Abstract operations quiz · 7 questionsScore: first tries count
              1. Question 1 of 7An object has no conversion hook. Number(obj) asks for a number. Which method is tried first?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does reading cart[3] print?

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

                Choose an answer to see the explanation.

              3. Question 3 of 7An object's valueOf gives 3n. What does ToNumeric give back?

                Choose an answer to see the explanation.

              4. Question 4 of 7What do these two comparisons print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                console.log("10" < "2", "10" < 2);

                Choose an answer to see the explanation.

              5. Question 5 of 7Why does IsLessThan take the yes-or-no input LeftFirst?

                Choose an answer to see the explanation.

              6. Question 6 of 7What does IteratorStep give back?

                Choose an answer to see the explanation.

              7. Question 7 of 7Is the array made by map an Orders list?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                class Orders extends Array { static get [Symbol.species]() { return Array; } }
                console.log(new Orders("tea").map(item => item) instanceof Orders);

                Choose an answer to see the explanation.

              If an answer surprised you, go back to the nearest example and run it. The order of conversions and the return() clean-up are easier to remember once you have seen the real output.

              Key takeaways

              Start from a line of JavaScript and follow only the rules it needs. The rules describe results you can test. They don't show what the engine does inside.

              • ToPrimitive turns an object into a primitive. It checks for Symbol.toPrimitive first. Then it tries valueOf and toString, in an order set by the hint.
              • ToPropertyKey gives a string or a Symbol. ToNumeric gives a number or a BigInt.
              • IsLooselyEqual (==) and IsLessThan (<) convert in different cases. The left value is always converted first.
              • GetIterator gets the iterator. IteratorStep checks done. IteratorStepValue also reads value when there is one.
              • SpeciesConstructor picks which class some new arrays are made from.

              Remember the one-liner.
              An abstract operation is a named rule in the spec, not a function your code can call.

              Coming next: Lexical grammar & ASI. It shows how JavaScript splits your code into words and symbols, before any of these rules can run.

              CompleteFrontend Clear concepts. Working examples.