Learn JavaScript

Lesson 5 of 9 · if, switch and Loops

Module 4 · if, switch and Loops

Under the Hood: Loops as Jumps, the Iterator Protocol and a Loop Lab

ProReading

Maria read a blog post that said for...of is slow, so "always write the index loop". She asks the question she always asks: "But why would it be slow?" Nobody on the team knows, and Kenji has already rewritten three loops. This lesson opens the engine, finds out what a loop really is, and then measures instead of guessing. The answer turns out to be "it depends", and you will see exactly on what.

Checking what this lesson needs for you…

What is inside Under the Hood: Loops as Jumps, the Iterator Protocol and a Loop Lab

  1. A loop is two jumps
  2. On-stack replacement: optimising a loop while it runs
  3. The iterator protocol behind for...of
  4. The loop lab: index, for...of, forEach and for...in
  5. A labelled break against a flag