Lesson 1: Modern JavaScript: strict mode, let, const and arrows
Working before it is written
A feature joins JavaScript only after it already works. TC39, the committee that writes the standard, asks for two things before a proposal reaches its last stage: two compatible implementations that pass Test262, the standard's own tests, and real experience with shipping implementations, such as two independent engines. So browsers often have a feature before the edition that names it.
Why it fits here: It explains this topic's advice to check MDN's tables: a feature reaches the engines first, and the yearly edition records it afterwards.
Source: TC39: The TC39 Process
Topic: How JavaScript changes · standards, tools
What ECMA stood for
The ECMA in ECMAScript was once a set of initials: European Computer Manufacturers Association. Ecma's own history says the association officially came into being on 17 May 1961. In 1994 it changed its name to Ecma International, to reflect its work around the world. Its standard ECMA-262, the one that defines JavaScript, reached its 17th edition in June 2026.
Why it fits here: It explains the odd name of this topic's standard: ECMAScript is named after the body that publishes it.
Sources: Ecma International: History; Ecma International: ECMA-262
Topic: How JavaScript changes · history, words
A switch written as a string
Strict mode is switched on by a plain string. The standard defines a Use Strict Directive as a statement that is only the text use strict, in double or single quotes, at the start of a script or a function. To an engine from before strict mode, that line is a string that does nothing, so old browsers run the code on. Even an escape sequence inside the text stops it counting.
Why it fits here: It answers this topic's question about the string: a keyword would have broken old browsers, while a string they could ignore.
Source: ECMAScript Language Specification: Directive Prologues and the Use Strict Directive
Topic: Strict mode: silent slips made loud · standards, tricks
Words kept for later
Strict mode also keeps a list of words free for the future. MDN lists them as newly reserved in anticipation of future language features: implements, interface, let, package, private, protected, public, static and yield cannot be names in strict code. Some have since found work, such as let. The standard still lists implements, interface, package, private, protected and public as future reserved words in strict code.
Why it fits here: It shows another job of this topic's strict mode: besides catching slips, it kept names free for the features ES2015 would bring.
Sources: MDN: Strict mode; ECMAScript Language Specification: Keywords and Reserved Words
Topic: Strict mode: silent slips made loud · standards, words
let in 2006
The keyword let reached a browser long before ES2015. On 24 October 2006 Mozilla released Firefox 2, and its release notes describe JavaScript 1.7, a language update with generators, iterators, array comprehensions, let expressions and destructuring assignments. The keyword let became part of the standard nine years later, in ES2015, whose section 13.3.1 is called Let and Const Declarations.
Why it fits here: It shows how long this topic's let waited: tried in one browser in 2006, it joined the standard only in 2015.
Sources: Mozilla: Firefox 2 Release Notes; Wikipedia: Firefox version history; ECMAScript 2015 Language Specification
Topic: let in loops: each turn its own counter · history, browsers
let for old browsers
Code with let can still run in browsers older than ES2015. Babel, a tool that converts ECMAScript 2015 and later into older JavaScript, rewrites let and const for them. For a loop whose turns make functions, its guide says the rewrite is impossible without adding an extra function and closure. That extra function gives each turn its own copy of the counter, as let does.
Why it fits here: It shows what this topic's let does underneath: to copy it with var, a tool must wrap each turn in a function of its own.
Sources: Babel: What is Babel?; Babel: @babel/plugin-transform-block-scoping
Topic: let in loops: each turn its own counter · tools, browsers
Three locks, from weak to strong
Object.freeze is the strongest of three locks. Object.preventExtensions only stops new properties from ever being added. Object.seal also stops properties being removed, though MDN notes that their values can still be changed as long as they are writable. Object.freeze stops changes to the values too, and MDN calls freezing the highest integrity level that JavaScript provides.
Why it fits here: It places this topic's Object.freeze at the top of a ladder: two lighter locks allow some changes that freeze forbids.
Sources: MDN: Object.preventExtensions(); MDN: Object.seal(); MDN: Object.freeze(); ECMAScript Language Specification: Object.seal
Topic: const, and freezing an object · standards, tools
Objects that refuse to freeze
Not every object can be frozen. MDN warns that a typed array or a DataView that holds elements throws a TypeError when frozen, because such objects are views over memory. A typed array, such as Uint8Array, is a list of raw numbers kept in a block of memory. An empty one freezes without complaint, since it has no elements to lock.
Why it fits here: It answers this topic's question: Object.freeze refuses objects whose elements are views over memory, and says so with a TypeError.
Sources: MDN: Object.freeze(); ECMAScript Language Specification: TypedArray [[DefineOwnProperty]]
Topic: const, and freezing an object · mistakes, standards
No break before the arrow
An arrow is strict about where its lines break. MDN warns that an arrow function cannot have a line break between its parameters and its arrow, and the standard's grammar marks the spot with the words no LineTerminator here. A break after the arrow is fine. Arrows also cannot be generators, the functions that pause with yield.
Why it fits here: It adds two limits to this topic's list of arrow differences: where the line may break, and no yield.
Sources: MDN: Arrow function expressions; ECMAScript Language Specification: Arrow Function Definitions
Topic: Arrow functions in depth · standards, mistakes
A fat arrow before ES2015
Arrows were tried out in another language first. CoffeeScript, a language that compiles to JavaScript, began with Jeremy Ashkenas's first commit on 13 December 2009. Its fat arrow, written =>, defined a function and bound it to the current value of this on the spot. In 2011 Brendan Eich named CoffeeScript as an influence on Eich's own thoughts about JavaScript's future.
Why it fits here: It gives this topic's arrows a forerunner: a language built on JavaScript had an arrow that kept this, years before ES2015.
Sources: Wikipedia: CoffeeScript; CoffeeScript
Topic: Arrow functions in depth · history, languages
Rule 8.1
Teams write their choices down. Airbnb's JavaScript style guide, rule 8.1, says that when you must use an anonymous function, as when passing an inline callback, you should use arrow notation. Its reason: the arrow runs in the context of this, which is usually what you want, and is shorter. Each rule names the ESLint checks that enforce it, so a tool can hold a team to it.
Why it fits here: It shows this topic's advice in a real team's rules: arrows for callbacks, written down and checked by a tool.
Source: Airbnb JavaScript Style Guide
Topic: Choosing the form for each job · tools, people
A tool that retires var
The habit of const by default has a checker. ESLint's prefer-const rule says that if a variable is never reassigned, const is better, because it tells readers the name will never change. Its no-var rule requires let or const instead of var. Both rules are fixable: run with the --fix option, ESLint rewrites much of the code by itself.
Why it fits here: It answers this topic's question about a tool: a linter can find each var and much of the time replace it for you.
Sources: ESLint: prefer-const; ESLint: no-var
Topic: Choosing the form for each job · tools, standards
Lesson 2: Template literals in depth
Where [object Object] comes from
The odd text [object Object] is built by a rule. When an object with no toString of its own becomes text, the standard's Object.prototype.toString joins the word object, the object's tag and square brackets. MDN explains that the tag is looked up with Symbol.toStringTag, so built-in kinds name themselves: a Map in a gap prints [object Map].
Why it fits here: It explains this topic's [object Object]: the words are a label built from the object's tag, never its contents.
Sources: ECMAScript Language Specification: Object.prototype.toString; MDN: Symbol.toStringTag
Topic: What a gap turns a value into · standards, mistakes
A null that vanishes
A gap and join disagree about null. In a template literal, null prints as the word null. But MDN notes that join turns an undefined or null element into an empty string instead of the words. An array's toString calls join, so an array in a gap shows empty places where its nulls were: [1, null, 3] prints as 1,,3.
Why it fits here: It warns about this topic's arrays in gaps: null prints as null on its own, but as nothing inside an array.
Sources: MDN: Array.prototype.join(); MDN: Array.prototype.toString(); ECMAScript Language Specification: Object.prototype.toString
Topic: What a gap turns a value into · mistakes, standards
Two line endings made one
Some text files end each line with two characters, a carriage return and a line feed, a habit from many early computer systems. Inside a template literal, the standard turns that pair, and a lone carriage return too, into a single line feed, \n. So the same template gives the same string on every computer. A real carriage return needs an explicit escape.
Why it fits here: It answers this topic's question: inside a template literal, every kind of line ending becomes the same line feed.
Sources: ECMAScript Language Specification: Template Literal Lexical Components; Wikipedia: Newline
Topic: Text over many lines · standards, tricks
A proposal to strip the indent
The indentation trap has a proposed cure. TC39's String.dedent proposal would remove the common leading indentation from multiline template strings, so text can be indented along with the code around it. Its status is Stage 2: it is still a proposal, not part of JavaScript yet, so for now the text must start at the left edge or be joined from lines.
Why it fits here: It shows that this topic's indentation trap bothers the language's own committee enough to plan a built-in fix.
Source: TC39: String dedent proposal
Topic: Text over many lines · standards, tools
Lakh and crore are built in
Browsers already know the lakh and the crore. MDN's own example of Intl.NumberFormat notes that India uses thousands, lakh and crore separators, and shows en-IN writing 1,23,456.789. The rules come from Unicode's CLDR, a shared store of locale data for programs around the world; its site lists Chrome and Android among the products that use it.
Why it fits here: It answers this topic's question: the Indian groups of en-IN come from a shared Unicode data store that browsers build in.
Sources: MDN: Intl.NumberFormat; Unicode CLDR Project
Topic: Numbers written for people · india, standards
A sign from 2010
The rupee sign is young. It was designed by D. Udaya Kumar, an Indian academic and designer, and first presented to the public by the Government of India on 15 July 2010, after an open competition. Unicode gave it the code point U+20B9 in version 6.0, on 12 October 2010, calling it the new official Indian currency symbol.
Why it fits here: It gives this topic's rupees a history: the ₹ that Intl.NumberFormat writes has existed in computers only since late 2010.
Sources: Wikipedia: Indian rupee sign; Unicode 6.0.0
Topic: Numbers written for people · india, history
Every letter the same width
Columns line up when every character takes the same width. The CSS standard defines a monospace font by exactly that: all glyphs have the same fixed width. The best known is Courier, designed in the mid-1950s by Howard Kettler for IBM. It was nearly called Messenger, until Kettler decided that a letter can be just an ordinary messenger, or it can be the courier.
Why it fits here: It explains why this topic's padded columns line up in the console: code is usually shown in a monospace font, where each character takes the same room.
Sources: CSS Fonts Module Level 4; Wikipedia: Courier (typeface)
Topic: Text in straight columns · history, people
Digits of equal width
A page can line up numbers without a monospace font. In many fonts the digits differ in width, so prices drift out of line. The CSS setting font-variant-numeric: tabular-nums switches on tabular numerals, figures that MDN describes as all of the same size, so they align as in tables. It suits a bill or a table of marks on a web page.
Why it fits here: It adds a tool for this topic's last advice: on a web page, tabular figures keep a column of numbers straight.
Sources: MDN: font-variant-numeric; CSS Fonts Module Level 4
Topic: Text in straight columns · tools, standards
Tags in the wild
Tags are not a curiosity: popular libraries are built on them. styled-components utilises tagged template literals to style React components, with real CSS written inside a template. Lit, a library for web components, writes its templates as template literals tagged with html. Both receive the pieces and the values separately, as every tag does.
Why it fits here: It answers this topic's question: styling and templating libraries use tags because a tag sees the pieces and the values apart.
Sources: styled-components: Basics; Lit: Templates overview
Topic: Tagged templates and String.raw · tools, internet
LaTeX loosened the rules
Tagged templates once refused text such as \unicode, because a backslash and u must start a proper escape. MDN explains the change with LaTeX, whose commands often start with u or x: the rule that escape sequences must be well formed was removed from tagged templates, so String.raw can hold LaTeX as written. TC39's list names the change Lifting template literal restriction, by Tim Disney.
Why it fits here: It shows why this topic's String.raw can hold any backslash: the rule was relaxed for tags so that other languages could live inside them.
Sources: MDN: Template literals; TC39: Finished Proposals
Topic: Tagged templates and String.raw · standards, languages
A browser that cleans HTML
Browsers have started to clean HTML themselves. Firefox 148 added the Sanitizer API, whose element.setHTML() inserts HTML much as innerHTML does, but without security holes such as cross-site scripting. MDN describes it as parsing and sanitizing the string, removing elements and attributes that are unsafe. MDN still marks it as limited availability: some widely used browsers lack it.
Why it fits here: It looks ahead from this topic's escaping: a built-in cleaner may one day do the work for markup that must keep its tags.
Sources: Mozilla: Firefox 148 Release Notes; MDN: Element.setHTML()
Topic: Building HTML that a name cannot break · browsers, privacy
And, by itself, and
The ampersand that must be escaped first has a name made of a sentence. When English letters were spelled aloud, a letter that was also a word was said with per se, Latin for by itself, and the sign & was called and per se and. Wikipedia explains that the phrase was slurred into ampersand, a word in common English use by 1837. The American Heritage Dictionary gives the same history.
Why it fits here: It names this topic's most important character: the ampersand, which must become an entity before any other sign does.
Sources: Wikipedia: Ampersand; The American Heritage Dictionary: ampersand
Topic: Building HTML that a name cannot break · words, history
Lesson 3: Destructuring and spread
Swapping, as Python does
Swapping two values in one line is an old idea. In the first program of Python's own tutorial, a multiple assignment gives two variables new values at once, and the tutorial notes that the right-hand side is all evaluated first, before any assignment takes place. JavaScript's [a, b] = [b, a] works the same way: the array on the right is built before either name changes.
Why it fits here: It explains why this topic's swap needs no spare variable: the new array on the right is complete before any name changes.
Source: Python documentation: An Informal Introduction to Python
Topic: Unpacking an array · languages, tricks
Any iterable will do
The square brackets work on more than arrays. MDN explains that array destructuring calls the iterable protocol of whatever stands on the right. So any iterable can be unpacked: a Map gives its pairs, a Set its members, a string its letters. javascript.info shows the string case, with three letters from abc. A plain object is not iterable, and cannot be unpacked with square brackets.
Why it fits here: It answers this topic's question: square brackets unpack anything that can be stepped through, not only arrays.
Sources: MDN: Destructuring; javascript.info: Destructuring assignment
Topic: Unpacking an array · standards, tricks
Braces that look like a block
An object pattern needs care when no const or let comes before it. MDN explains that { a, b } = obj on a line of its own is not valid, because the braces are read as a block, not as an object. The standard forbids an expression statement from starting with a brace. Wrapped in round brackets, ({ a, b } = obj) works.
Why it fits here: It warns about this topic's object patterns: with no const or let in front, the whole assignment needs round brackets.
Sources: MDN: Destructuring; ECMAScript Language Specification: Expression Statement
Topic: Unpacking an object · standards, mistakes
A name from the prototype
Unpacking reads a property the way a dot does, so it can find names that an object only inherits. MDN notes that when an object does not have a property itself, the lookup continues along the prototype chain. So const { toString } = {} gives a function, though the empty object has no properties of its own. The standard's steps read each name with GetV, an ordinary property lookup.
Why it fits here: It warns about this topic's object patterns: a name can come back filled from the object's prototype, not from the object itself.
Sources: MDN: Destructuring; ECMAScript Language Specification: Runtime Semantics: KeyedBindingInitialization
Topic: Unpacking an object · standards, tricks
Named arguments, JavaScript style
Some languages let a call name its arguments. Python's tutorial shows functions called with keyword arguments of the form kwarg=value, in any order. A destructured parameter gives JavaScript the same effect: book({ seats: 2, train: "Rajdhani" }) names each value, the order no longer matters, and a value left out takes its default.
Why it fits here: It answers this topic's question: one object, unpacked in the parameter, lets a JavaScript call name its arguments.
Sources: Python documentation: More Control Flow Tools; MDN: Destructuring
Topic: Unpacking in parameters and loops · languages, tricks
Every React component does this
React's components are written with this topic's patterns. React's own guide declares a component as function Avatar({ person, size }) and explains that this syntax is called destructuring, equivalent to reading properties from a function parameter. A default works the same way inside the pattern: size = 100 gives a size whenever none is passed.
Why it fits here: It shows this topic's parameter patterns in a library used on a great many sites: every component unpacks its props this way.
Source: React: Passing Props to a Component
Topic: Unpacking in parameters and loops · tools, internet
Rest goes last
The three dots must come last. MDN warns that the rest element must be the last in the pattern, and must not even have a trailing comma after it. So [a, ...b,] is a SyntaxError, whose message says that a rest element may not have a trailing comma. A rest element takes everything that is left, so nothing could ever come after it.
Why it fits here: It answers this topic's question: nothing may follow the dots, not even a comma, because the rest takes all that remains.
Sources: MDN: Destructuring; ECMAScript 2018 Language Specification
Topic: Gathering the rest · standards, mistakes
Objects waited three years
Rest and spread worked on arrays in ES2015, but on objects only later. TC39's list of finished proposals names Rest/Spread Properties, championed by Sebastian Markbåge, and the 2018 edition of the standard defines CopyDataProperties, the step that copies an object's properties while leaving out the ones already named. So { a, ...others } is a younger feature than [a, ...others].
Why it fits here: It dates this topic's object rest: the three dots reached objects in 2018, three years after arrays.
Sources: TC39: Finished Proposals; ECMAScript 2018 Language Specification
Topic: Gathering the rest · history, standards
Nothing to spread
Spreading null behaves in two different ways. In an array or a call, ...null throws a TypeError: MDN's error page lists spreading into an array or a function call among the places where a value must be iterable. In an object literal, { ...null } is fine and adds nothing, because the standard's copying step stops at once when the source is undefined or null.
Why it fits here: It sharpens this topic's spread: in arrays and calls the value must be iterable, while object spread quietly skips null and undefined.
Sources: MDN: TypeError: 'x' is not iterable; ECMAScript Language Specification: CopyDataProperties
Topic: Spreading values out · standards, mistakes
Before the dots: apply
Laying out an array as arguments was possible long before the three dots. The third edition of the standard, in 1999, already had Function.prototype.apply, which takes the arguments as an array: Math.max.apply(null, list). MDN still calls it common to use apply when the elements of an array should be a function's arguments, and shows spread syntax doing the same job more plainly.
Why it fits here: It explains a line often met in older code: apply did this topic's spread job, with an extra first argument for this.
Sources: ECMAScript Language Specification, 3rd edition (December 1999); MDN: Spread syntax
Topic: Spreading values out · history, standards
Spread changes nothing it copies
Spread and Object.assign look alike but behave differently. MDN notes that Object.assign can change the object it copies into, and triggers that object's setters, while spread syntax triggers no setters and changes no object: it always builds a new one. For this topic's copy-and-update, spread is the safer of the two.
Why it fits here: It explains why this topic copies with spread: the original object is never touched, and no hidden setter runs.
Sources: MDN: Spread syntax; ECMAScript 2018 Language Specification
Topic: Copying and updating objects · standards, mistakes
Copying only what changed
Deep updates with spread grow long: every level on the way down must be copied by hand. Redux Toolkit wraps its update functions in a library called Immer, so a nested update can be written as one plain assignment. Its documentation says Immer copies exactly the levels that changed, as a careful chain of spreads would, and leaves the rest shared.
Why it fits here: It answers this topic's question: tools such as Immer do the level-by-level copying that this topic does by hand.
Source: Redux: Immutable Update Patterns
Topic: Copying and updating objects · tools, internet
Lesson 4: Modules
Iffy
Before modules, programmers hid names inside a function that ran at once. On 15 November 2010 Ben Alman proposed a name for the pattern: Immediately-Invoked Function Expression, IIFE for short. Someone suggested the pronunciation iffy, and Alman liked it. Code wrapped in (function () { ... })() kept its names private, the job a module now does by itself.
Why it fits here: It answers this topic's question: before modules, a function that ran at once was the usual way to keep names private.
Source: Ben Alman: Immediately-Invoked Function Expression (IIFE)
Topic: Why modules · history, words
require before import
Modules for JavaScript began outside the browser. In January 2009 the Mozilla engineer Kevin Dangoor started a project called ServerJS, renamed CommonJS that August to show its wider use. Its require became, in the words of Node's documentation, the original way to package JavaScript code for Node.js. The standard's own import and export came six years later, with ES2015.
Why it fits here: It explains the two module systems met in Node: require came first, from CommonJS, and the standard's import came later.
Sources: Wikipedia: CommonJS; Node.js documentation: Modules: CommonJS modules; ECMAScript 2015 Language Specification
Topic: Why modules · history, people
Shaking the tree
Because exports are written plainly, tools can read them without running the code. Rollup, a tool that bundles modules into one file, statically analyzes the code you import and excludes anything that is not actually used; its own guide calls this tree shaking. So a module that exports fifty helpers costs a page only the few that it imports.
Why it fits here: It answers this topic's question: since exports are fixed in the code, a tool can see which are never imported and leave them out.
Source: Rollup: README
Topic: Exporting: what a file lends · tools, internet
A package that lends only some files
A whole package can choose what it lends, as a file does. Node's documentation describes the exports field of package.json: once a package defines it, other code cannot reach any entry point that it does not list, not even the package.json itself. Node warns that adding the field to an existing package is likely to break code that used the hidden files.
Why it fits here: It shows this topic's rule one level up: a package, like a file, can keep everything private except what it lists.
Source: Node.js documentation: Modules: Packages
Topic: Exporting: what a file lends · tools, standards
JSON by import
A module can now import a JSON file straight into an object: import data from "./data.json" with { type: "json" }. MDN marks import attributes as Baseline 2025, working in the latest browsers since April 2025, and the json type says the file must contain JSON. TC39's list of finished proposals names Import Attributes, by Myles Borins, Sven Sauleau, Dan Clark and Daniel Ehrenberg.
Why it fits here: It answers this topic's question: with an attribute saying the file is JSON, a module imports a data file as an object.
Sources: MDN: Import attributes; TC39: Finished Proposals
Topic: Importing: what a file borrows · standards, tools
An object you cannot change
An import * as maths gives an object, but an unusual one. MDN describes the namespace object as a sealed object with a null prototype: nothing can be added to it, and it has none of the usual object methods. The standard says it exposes the bindings exported from a module, so its properties are live exports that the importer can read but never assign.
Why it fits here: It sharpens this topic's namespace objects: the object stands for the module itself, so it cannot be changed from outside.
Sources: MDN: import; ECMAScript Language Specification: Module Namespace Exotic Objects
Topic: Importing: what a file borrows · standards, mistakes
Two guides, two answers
Big style guides disagree about defaults. Google's JavaScript style guide says to use named exports in all code and not to use default exports, since importers must give them names, which can lead to inconsistent naming across modules. Airbnb's guide, rule 10.6, says the opposite for a module with a single export: prefer a default export, for readability.
Why it fits here: It answers this topic's question: even large companies split on default exports, which is why this topic gives a reason for its choice.
Sources: Google JavaScript Style Guide; Airbnb JavaScript Style Guide
Topic: Default exports · tools, people
default is just a name
The words export default are a shortcut for a name. MDN shows export { myFunction as default }, an ordinary named export whose name is default, and the standard gives every default export the name default. MDN adds that in a namespace object the default export is a key called default. So import { default as clock } works too.
Why it fits here: It explains how this topic's braces-free import works: it borrows the export that is named default.
Sources: MDN: export; MDN: import; ECMAScript Language Specification: Static Semantics: ExportedNames
Topic: Default exports · standards, tricks
Bare names with an import map
A page can teach the browser what a bare name means. An import map is a JSON object, in a script with the type importmap, that controls how the browser resolves module specifiers. It can say that confetti means a file at a certain address. MDN shows import maps working across browsers since March 2023, and the HTML standard defines them.
Why it fits here: It answers this topic's question: an import map lets a page use bare names, by saying which file each name means.
Sources: MDN: script type="importmap"; WHATWG: HTML Standard, import maps
Topic: Loading modules in a browser and in Node · standards, browsers
A script for old browsers
Pages once shipped two versions of their code. A script with the nomodule attribute runs only in browsers that do not support modules, so it can carry a fallback for older browsers. The HTML standard explains the pair: module scripts run in modern browsers, and classic scripts with nomodule run in older ones, while each browser skips the other.
Why it fits here: It shows how this topic's type="module" was rolled out: old browsers ignored it, and nomodule gave them something else to run.
Sources: MDN: script; WHATWG: HTML Standard, the script element
Topic: Loading modules in a browser and in Node · browsers, tricks
The cost of a barrel
A file that only re-exports others is called a barrel file, and it has a cost. Vite's guide explains that importing one function through a barrel makes the browser load every file behind it, more files than the page needs, so the page loads more slowly. Its advice is to avoid barrel files where possible, and import what you need from its own file.
Why it fits here: It answers this topic's question: export ... from is handy, but a barrel can make a page load files it never uses.
Source: Vite: Performance
Topic: Arranging a project's files · tools, mistakes
Loading later, since 2020
A page can load a module only when it is needed, such as when a button is pressed. MDN calls import() a function-like expression that loads a module asynchronously; its promise fulfils to a module namespace object. TC39's list of finished proposals names import(), by Domenic Denicola, and the standard's 2020 edition defines it as an ImportCall.
Why it fits here: It dates this topic's import(): loading a module on demand became standard JavaScript in 2020.
Sources: MDN: import(); TC39: Finished Proposals; ECMAScript 2020 Language Specification
Topic: Arranging a project's files · standards, history
Lesson 5: Classes
Called without new
A class refuses to be called like a plain function. MDN explains that all class constructors must be called with new, and that calling one without it throws a TypeError. The standard's steps create that TypeError the moment a class constructor is called. Older constructor functions had no such guard: JavaScript functions were used both as constructors and as normal functions.
Why it fits here: It explains this topic's rule about new: a class cannot be called without it, so the slip is caught at once.
Sources: MDN: TypeError: class constructors must be invoked with 'new'; ECMAScript Language Specification: [[Call]] of ECMAScript function objects
Topic: A class and its objects · standards, mistakes
instanceof and frames
instanceof does not ask about a class's name: it looks for the class's prototype along the object's prototype chain. MDN shows the surprise this causes. Each window or frame has its own built-ins, so an array made in the page fails instanceof the Array of a frame inside it. MDN's answer is Array.isArray, which says whether a value is an array whichever realm it came from.
Why it fits here: It sharpens this topic's instanceof: it compares prototypes, so the same class from another frame does not count.
Sources: MDN: instanceof; ECMAScript Language Specification: OrdinaryHasInstance
Topic: A class and its objects · standards, browsers
Why the hash
The # in a private name has a reason. The FAQ of TC39's class fields proposal explains that a private field named x must not stop an object from also having a public field named x, so reading a private field cannot be an ordinary lookup. It adds that this is an issue only because JavaScript lacks static types. Typed languages can tell the two apart; JavaScript lets the name carry the mark.
Why it fits here: It answers this topic's question: a keyword could not tell a private x from a public x at run time, so the name itself is marked.
Source: TC39: Class fields proposal, Private Syntax FAQ
Topic: Fields: public and private · standards, languages
Asking whether a field is there
A class can ask whether an object has one of its private fields. MDN shows #x in obj, which checks for a private element without the TypeError that reading a missing one would throw. The 2022 edition of the standard has the grammar for it, a private name before in, and TC39's list of finished proposals calls it ergonomic brand checks for private fields.
Why it fits here: It gives this topic's private fields a safe test: #x in obj says whether the field is there, without throwing.
Sources: MDN: in; ECMAScript 2022 Language Specification; TC39: Finished Proposals
Topic: Fields: public and private · standards, tricks
Getters before classes
Getters are older than classes. The 5.1 edition of the standard, from June 2011, already let an object literal hold get and set definitions. A non-standard method, __defineGetter__, does the same job: it binds a property to a function that is called when the property is looked up. MDN marks it as deprecated in favour of the get syntax and Object.defineProperty.
Why it fits here: It shows that this topic's get and set inside a class reuse syntax that plain objects had years earlier.
Sources: ECMAScript 5.1 Language Specification; Ecma International: ECMA-262; MDN: Object.prototype.__defineGetter__()
Topic: Getters and setters · history, standards
Setters that redraw the page
Getters and setters once powered a whole framework. Vue 2's guide explains that it walks through every property of a component's data and converts each one into a getter and setter with Object.defineProperty. Reading or writing a property then lets Vue track what depends on what, and update the page. The guide adds that this ES5-only feature is why Vue 2 does not support IE8 and below.
Why it fits here: It answers this topic's question: Vue 2 put a setter on every data property, so each assignment could trigger an update of the page.
Source: Vue.js 2 Guide: Reactivity in Depth
Topic: Getters and setters · tools, internet
Math, all static
The best-known statics belong to an object that is not a class at all. MDN explains that Math is not a constructor: it cannot be used with new or called as a function, and all of its properties and methods are static. The standard says the same in its own words: Math cannot be used as a constructor with the new operator. So Math.max and Math.PI are used on Math itself.
Why it fits here: It answers this topic's question: Math works like a class made only of statics, though it is a plain object.
Sources: MDN: Math; ECMAScript Language Specification: The Math Object
Topic: Static methods and fields · standards, maths
A block that runs once
A class can run setup code of its own, once. A static initialization block, written static { ... } inside the class body, holds statements evaluated while the class is set up. MDN says this allows more flexible setup than static fields alone, such as a try...catch. TC39's list of finished proposals names Class Static Block, by Ron Buckton.
Why it fits here: It extends this topic's statics: besides static methods and fields, a class can hold a block of setup code that runs once.
Sources: MDN: Static initialization blocks; TC39: Finished Proposals
Topic: Static methods and fields · standards, tools
Built-ins can be extended
A class can be built on JavaScript's own built-ins. MDN notes that extends can subclass custom classes as well as built-in objects, so class Basket extends Array gives an array with methods of its own. Any constructor that can be called with new and has a prototype property can be the parent. The standard's grammar allows any expression of the right kind after extends.
Why it fits here: It widens this topic's extends: a class can build on Array or Error as easily as on a class of your own.
Sources: MDN: extends; ECMAScript Language Specification: Class Definitions
Topic: One class built on another · standards, tricks
Extending an expression
The word after extends need not be a name. MDN explains that any expression that evaluates to a constructor may follow it, which is often used to make mixins: functions that take a class and return a new class built on it. A class can have only one parent, so mixins are how code collects abilities from several places, one layer at a time.
Why it fits here: It shows a trick built on this topic's extends: since one parent is the limit, functions can stack abilities onto classes.
Sources: MDN: extends; ECMAScript Language Specification: Class Definitions
Topic: One class built on another · standards, tricks
When instanceof broke
Compiling code for old browsers once broke error classes. TypeScript's notes on breaking changes explain that when classes are compiled to older JavaScript, subclassing Error may no longer work as expected: new FooError() instanceof FooError returns false. Their advice was to set the prototype by hand right after the super(...) call. Code compiled to modern JavaScript keeps real classes, where instanceof works.
Why it fits here: It explains odd advice in older code: a line that fixes the prototype after super, needed only when classes were compiled away.
Source: TypeScript wiki: Breaking Changes
Topic: Error classes of your own · tools, mistakes
A code, not a message
Node.js names its errors with codes as well as messages. Its documentation says the code property is a string label that identifies the kind of error, and the most stable way to identify one: a code changes only between major versions, while message text may change in any version. So code that catches a Node error should test err.code, not the words of its message.
Why it fits here: It adds a habit to this topic's own error classes: give each kind a stable name or code to test, and leave messages free to change.
Source: Node.js documentation: Errors
Topic: Error classes of your own · tools, standards
Lesson 6: Iterators and higher-order functions
Functions about functions, 1930s
Functions that take and return functions come from mathematics. Alonzo Church introduced the lambda calculus in the 1930s, as part of research into the foundations of mathematics. The Stanford Encyclopedia of Philosophy calls it, at heart, a simple notation for functions and application, built on two ideas: applying a function to an argument, and forming new functions.
Why it fits here: It gives this topic's higher-order functions their root: functions treated as values began in a 1930s notation for mathematics.
Sources: Wikipedia: Lambda calculus; Stanford Encyclopedia of Philosophy: The Lambda Calculus
Topic: Functions that take and give functions · history, maths
One logician, two names
Turning f(a, b) into f(a)(b), one function per argument, is called currying, after the logician Haskell Curry. A programming language carries the first name too: the Haskell report says the language is named after the logician Haskell B. Curry, whose work provides the logical basis for much of it. So one logician named both a technique and a language.
Why it fits here: It answers this topic's question: a function that gives back a function, one argument at a time, is called currying after Haskell Curry.
Sources: Wikipedia: Currying; Haskell 2010 Language Report: Preface
Topic: Functions that take and give functions · people, languages
The same letters, two orders
Sorting words depends on the language. MDN's example of localeCompare shows ä sorting before z in German, but after z in Swedish. The Unicode Collation Algorithm, the standard behind such sorting, puts it in one line: Germans, French and Swedes sort the same characters differently. It adds that even within one language, dictionaries may sort differently from phone books.
Why it fits here: It answers this topic's question, and explains why localeCompare takes a locale: the right order depends on the reader's language.
Sources: MDN: String.prototype.localeCompare(); Unicode Technical Standard #10: Unicode Collation Algorithm
Topic: Chains, finding and sorting · standards, words
Searching from the end
Searching an array from its end got methods of its own only recently. TC39's list of finished proposals names Array find from last, by Wenlu Wang, which added findLast and findLastIndex beside find and findIndex. MDN shows findLast working across browsers since August 2022. Before them, code reversed a copy of the array first, or wrote a loop that counted down.
Why it fits here: It completes this topic's find and findIndex: findLast and findLastIndex search the same way, starting from the end.
Sources: TC39: Finished Proposals; MDN: Array.prototype.findLast()
Topic: Chains, finding and sorting · standards, tools
Borrowed from Perl
JavaScript's regular expressions were not invented for it. The standard states that their form and functionality are modelled after the regular expression facility in the Perl 5 programming language. So \d, + and {6} mean in JavaScript what they mean in Perl, and a pattern learnt for one often reads the same in the other.
Why it fits here: It explains where this topic's pattern symbols come from: JavaScript took them from Perl 5.
Source: ECMAScript Language Specification: RegExp (Regular Expression) Objects
Topic: Patterns in text: regular expressions · languages, standards
A pattern that slowed a network
One regular expression once slowed a large part of the web. On 2 July 2019 Cloudflare deployed a new firewall rule that exhausted every processor core handling web traffic across its network. Its report gives the cause: the update contained a regular expression that backtracked enormously, trying so many ways to match that the processors had no time left for anything else.
Why it fits here: It answers this topic's question: a badly built pattern can take a very long time on some text, so test patterns on long inputs too.
Source: Cloudflare Blog: Details of the Cloudflare outage on July 2, 2019
Topic: Patterns in text: regular expressions · internet, mistakes
Python's iterators, 2001
JavaScript's iteration protocol has an older cousin. Python's PEP 234, created on 30 January 2001 by Ka-Ping Yee and Guido van Rossum, proposed an iteration interface that objects can provide to control the behaviour of for loops: a method that produces an iterator object. JavaScript's Symbol.iterator, which returns an object with a next method, works on the same plan.
Why it fits here: It answers this topic's question: Python's for loops asked objects for iterators years before JavaScript's for...of did.
Source: Python: PEP 234, Iterators
Topic: How for...of walks a value · languages, history
map and filter for any iterator
Iterators gained array-like methods in 2025. TC39's list of finished proposals names Sync Iterator helpers, and MDN shows Iterator.prototype.map working in the latest browsers since March 2025. So map, filter and take can now run on any iterator, such as one from a generator, without first copying its values into an array.
Why it fits here: It extends this topic's chains to iterators: the array methods now have iterator versions that work one value at a time.
Sources: TC39: Finished Proposals; MDN: Iterator.prototype.map()
Topic: How for...of walks a value · standards, tools
Async before async
Generators once did the work that async functions do now. The co library describes itself as generator based control flow for Node.js and the browser, using promises, letting you write non-blocking code. Inside it, a line such as var result = yield Promise.resolve(true) waited for a promise, much as await does today. Its readme calls it a stepping stone towards the async/await proposal.
Why it fits here: It shows how far this topic's generators reach: pausing at yield was the trick that later became await.
Source: co: README
Topic: Generators: values one at a time · history, tools
yield came from CLU
The word yield is older than JavaScript. CLU, a language whose project Barbara Liskov led, had iterators that handed each value to the caller with a yield statement. Liskov's history of CLU counts its iterators among its interesting and influential features. Wikipedia dates generators in CLU to 1975 and notes that such iterators are now common, often called generators.
Why it fits here: It answers this topic's question: CLU paused and resumed with yield decades before JavaScript's generators did.
Sources: Barbara Liskov: A History of CLU; Wikipedia: CLU (programming language); Wikipedia: Generator (computer programming)
Topic: Generators: values one at a time · history, languages
The hook for-of calls
Symbol.iterator is one of the standard's well-known symbols, a short list of hooks that built-in syntax looks for. The standard's table describes it as a method that returns the default iterator for an object, called by the semantics of the for-of statement. MDN adds that whenever an object needs to be iterated, this method is called with no arguments.
Why it fits here: It explains this topic's *[Symbol.iterator](): it is the one hook that for...of looks for on any object.
Sources: ECMAScript Language Specification: Well-Known Symbols; MDN: Symbol.iterator
Topic: Objects that for...of can walk · standards, tricks
One object, both roles
A generator object plays two parts at once. The standard says it conforms to both the iterator interface and the iterable interface, and MDN says the same: it has a next method, and for...of can also walk it. That is why a generator method can serve as an object's Symbol.iterator, and why a generator, once walked to the end, gives nothing more.
Why it fits here: It answers this topic's question: the generator a generator method returns is both the iterator and the iterable that for...of needs.
Sources: ECMAScript Language Specification: Generator Objects; MDN: Generator
Topic: Objects that for...of can walk · standards, tricks
Lesson 7: Promises
A number here, an object there
The value setTimeout gives back depends on where the code runs. In a browser, MDN says it is a positive integer that identifies the timer, to be passed to clearTimeout. In Node.js it is a Timeout object, which Node's documentation says is created internally and can be passed to clearTimeout too. Node adds that it makes no guarantees about the exact timing of callbacks.
Why it fits here: It warns about this topic's setTimeout: keep its result only to cancel the timer, since its type differs between browsers and Node.js.
Sources: MDN: Window.setTimeout(); Node.js documentation: Timers
Topic: Code that runs later · browsers, tools
Timers in hidden tabs
A page in a hidden tab gets fewer turns. Chrome 88 added what its team calls intensive throttling. When a page has been hidden for more than 5 minutes, has been silent for at least 30 seconds, and chains its timers five or more deep, the browser checks those timers only once per minute. Timers due within that minute then run together.
Why it fits here: It warns about this topic's timers: the delay is only a minimum, and a hidden tab may wait far longer than asked.
Source: Chrome for Developers: Heavy throttling of chained JS timers beginning in Chrome 88
Topic: Code that runs later · browsers, numbers
An open standard for promises
Promises were used in JavaScript before the language had them. MDN notes that the ecosystem had made many promise implementations long before promises became part of the language. Their authors agreed on Promises/A+, which calls itself an open standard for sound, interoperable JavaScript promises, and defines a promise as the eventual result of an asynchronous operation.
Why it fits here: It answers this topic's question: promise libraries came first, and agreed on a shared standard before JavaScript adopted promises.
Sources: MDN: Promise; Promises/A+
Topic: What a promise is · history, standards
jQuery's Deferred, 2011
jQuery offered something like promises early on. Its Deferred object, added in version 1.5, is described as a chainable utility object that registers callbacks and relays the success or failure state of an asynchronous function. John Resig announced jQuery 1.5 on 31 January 2011, four years before ES2015 gave JavaScript its own Promise.
Why it fits here: It shows this topic's promise idea in older code: jQuery's Deferred played the same part long before the built-in Promise.
Sources: jQuery API Documentation: jQuery.Deferred(); Official jQuery Blog: jQuery 1.5 Released
Topic: What a promise is · history, tools
Anything with a then
A promise chain accepts more than real promises. Promises/A+ defines a thenable as an object or function that defines a then method, and MDN explains that all promise-like objects implement this thenable interface. So returning any thenable from then makes the chain wait for it, whichever library made it.
Why it fits here: It answers this topic's question: then looks only for a then method, so a thenable from any library works.
Sources: Promises/A+; MDN: Promise
Topic: Chains of then · standards, tricks
finally, since 2018
The finally step is younger than then and catch. The 2018 edition of the standard defines Promise.prototype.finally, which MDN describes as scheduling a function to be called when the promise is settled, whether fulfilled or rejected. MDN adds that it lets you avoid duplicating the same code in both a then and a catch.
Why it fits here: It dates this topic's finally: the clean-up step that runs either way joined the standard in 2018.
Sources: ECMAScript 2018 Language Specification; MDN: Promise.prototype.finally()
Topic: Chains of then · standards, history
Node stops on a forgotten rejection
Node.js changed its mind about forgotten promises. As of Node.js 15, its release notes say, the default mode for an unhandled rejection changed from warn to throw. Unless the program sets an unhandledRejection hook, the rejection is raised as an uncaught exception, which ends the program. A missing catch now fails loudly.
Why it fits here: It answers this topic's question: a rejection with no catch now stops a Node.js program, so a final catch matters.
Source: Node.js blog: Node.js 15.0.0
Topic: Failures, caught in one place · tools, mistakes
An event for forgotten rejections
Browsers announce a rejection that nobody caught. MDN explains that the unhandledrejection event is sent to the global scope when a promise with no rejection handler is rejected, which helps with debugging and with fallback error handling. The HTML standard fires it at the global object as a PromiseRejectionEvent, which carries the promise and the reason.
Why it fits here: It gives this topic's Uncaught report a hook: a page can listen for unhandledrejection and log every forgotten failure.
Sources: MDN: Window: unhandledrejection event; WHATWG: HTML Standard, unhandled promise rejections
Topic: Failures, caught in one place · browsers, standards
Resolve from outside
A newer method hands over a promise with its controls. MDN describes Promise.withResolvers() as returning an object with a new promise and the two functions that resolve or reject it, so code outside the promise's own function can settle it. TC39's list of finished proposals names it, by Peter Klecha, and MDN shows it working across browsers since March 2024.
Why it fits here: It answers this topic's question: one call now gives a promise together with its resolve and reject functions.
Sources: MDN: Promise.withResolvers(); TC39: Finished Proposals
Topic: Many promises at once · standards, tools
Promise.try, 2025
Starting a chain with code that may throw got easier in 2025. MDN describes Promise.try as taking a callback of any kind, one that returns or throws, at once or later, and resolving its result to a promise, so even a thrown error becomes a rejection for catch. MDN shows it working in the latest browsers since January 2025, and TC39 lists it as finished.
Why it fits here: It adds a tool for this topic's chains: Promise.try turns any function's result, or its error, into a promise.
Sources: MDN: Promise.try(); TC39: Finished Proposals
Topic: Many promises at once · standards, tools
The post that explained the order
One blog post became the classic explanation of this topic. On 17 August 2015 Jake Archibald published Tasks, microtasks, queues and schedules. It explains that microtasks are usually scheduled for things that should happen straight after the code that is running, such as reacting to a batch of actions, without the cost of a whole new task.
Why it fits here: It points to a classic guide on this topic's order: running code, then microtasks, then the next task.
Source: Jake Archibald: Tasks, microtasks, queues and schedules
Topic: What runs next: the event loop · people, internet
A microtask of your own
Code can add to the microtask queue directly. The HTML standard's queueMicrotask() lets a page schedule a callback on the microtask queue, to run once all the code running now has finished. MDN calls it queuing a microtask to be executed at a safe time, before control returns to the browser's event loop.
Why it fits here: It answers this topic's question: queueMicrotask puts a callback in the same queue as promise callbacks, with no promise at all.
Sources: WHATWG: HTML Standard, microtask queuing; MDN: Window.queueMicrotask()
Topic: What runs next: the event loop · standards, tricks
Lesson 8: async and await
Older in C#
async and await were not invented for JavaScript. Microsoft's history of C# says that version 5.0, released in August 2012, put nearly all of its effort into the async and await model for asynchronous programming. Wikipedia adds that F# had asynchronous workflows with await points in 2007, and that Python and TypeScript took up async and await in 2015, before JavaScript did.
Why it fits here: It answers this topic's question: the async and await keywords reached JavaScript after C#, F#, Python and TypeScript had them.
Sources: Microsoft Learn: The history of C#; Wikipedia: Async/await
Topic: Async functions · history, languages
async functions, 2017
JavaScript's async functions arrived in the 2017 edition of the standard, whose section 14.6 is called Async Function Definitions. TC39's list of finished proposals names Async functions, by Brian Terlson. Before them, code wrote chains of then. An async function keeps the promise underneath: it always gives one back, whatever its body returns.
Why it fits here: It dates this topic's async functions: they joined the standard in 2017, two years after promises.
Sources: ECMAScript 2017 Language Specification; TC39: Finished Proposals
Topic: Async functions · standards, history
Even await 5 waits
await always takes a turn. MDN explains that when the awaited value is ready, another microtask is scheduled to continue the paused code, even if the value is an already-resolved promise or not a promise at all. The standard's steps show why: await first turns any value into a promise, with PromiseResolve. So code after await 5 runs only after other queued microtasks.
Why it fits here: It answers this topic's question: await on a plain value still pauses for one turn, so the code after it runs later.
Sources: MDN: await; ECMAScript Language Specification: Await
Topic: await: pause here, and carry on after · standards, mistakes
A bug that made await faster
await got faster thanks to a bug. V8's team writes that Node.js 8 had a bug that caused await to skip microticks in some cases, which made programs faster. The bug started as an unintended break from the standard, but it later gave the team the idea for an optimization, and V8 went on to remove two extra microticks from every await.
Why it fits here: It shows that this topic's await has a cost in microtasks, and that engine makers worked to make it smaller.
Source: V8 blog: Faster async functions and promises
Topic: await: pause here, and carry on after · tools, history
A lint rule that changed its mind
ESLint once had a rule against return await, and then retired it. The rule was deprecated in ESLint v8.46.0, with no replacement. Its page now explains why: return await on a promise no longer causes an extra microtask, and it gives a better stack trace for debugging. The old advice came from the early days of promises, when the extra step did cost time.
Why it fits here: It answers this topic's question, and backs its advice to write return await inside a try: the cost is gone, and the error trace is better.
Source: ESLint: no-return-await
Topic: Failures with try and catch · tools, history
Traces across await
An error thrown after several awaits can still show how it got there. V8's team writes that Chrome DevTools supports async stack traces, which include the asynchronous part of the stack as well as the current one. Logs on a server see only Error#stack, so V8 built zero-cost async stack traces, which add the async function calls to it, through await and Promise.all.
Why it fits here: It helps with this topic's failures: the trace of an error can list the async calls that led to it, not only the last step.
Source: V8 blog: Faster async functions and promises
Topic: Failures with try and catch · tools, browsers
Six at a time
Starting jobs together has a limit inside the browser. Chrome's DevTools reference lists one reason a request waits in a queue: there are already six TCP connections open for this origin, which is the limit, a rule that applies to HTTP/1.0 and HTTP/1.1 only. So a hundred requests started together to an old server still go about six at a time.
Why it fits here: It answers this topic's question: requests started together to one HTTP/1.1 server still run about six at a time.
Source: Chrome for Developers: Network features reference
Topic: One at a time, or together · browsers, numbers
A request with a deadline
A job awaited with others can be given a deadline. AbortSignal.timeout(ms) returns a signal that aborts by itself after the given time, with a TimeoutError; passed to fetch, it stops a slow request. MDN shows it working across browsers since April 2024, and the DOM standard defines the steps that make the signal.
Why it fits here: It adds a guard to this topic's Promise.all: one slow job can be given a time limit, so the whole group need not wait for ever.
Sources: MDN: AbortSignal.timeout(); WHATWG: DOM Standard
Topic: One at a time, or together · standards, tools
await in the Console, 2017
The browser's Console allowed await on its own line years before modules did. Chrome's notes on DevTools in Chrome 62, last updated in August 2017, announce support for top-level await operators in the Console. So typing await fetch(url) there works without an async function around it. Modules gained the same freedom later, as this topic shows.
Why it fits here: It gives a handy use of this topic's top-level await: in the browser's Console, await works on a line of its own.
Source: Chrome for Developers: What's New In DevTools (Chrome 62)
Topic: await outside a function · tools, browsers
No flag since August 2020
Node.js let modules use top-level await without a flag in version 14.8.0. Its release notes, updated on 11 August 2020, list the change as module: unflag Top-Level Await, by Myles Borins, who also championed the proposal. Before that, the feature needed a special command-line flag to switch it on.
Why it fits here: It answers this topic's question: Node.js ran top-level await without a flag from version 14.8.0, in August 2020.
Source: Node.js blog: Node.js 14.8.0
Topic: await outside a function · tools, history
Streams you can walk
Node.js streams can be read with this topic's loop. Its documentation lists readable[Symbol.asyncIterator](), added in version 10.0.0, so for await...of can read a file stream chunk by chunk. If the loop ends with a break, a return or a throw, the documentation says, the stream is destroyed, so nothing more is read.
Why it fits here: It answers this topic's question: Node's readable streams are async iterables, so for await...of reads them piece by piece.
Source: Node.js documentation: Stream
Topic: Values that arrive slowly · tools, standards
Collecting it all at once
Collecting every value of an async source into an array has its own method. MDN describes Array.fromAsync() as creating a new array from an async iterable, an iterable or an array-like object, and shows it working across browsers since January 2024. TC39's list of finished proposals names it, by J. S. Choi.
Why it fits here: It gives the other end of this topic's async generators: when every value is wanted, one call collects them all.
Sources: MDN: Array.fromAsync(); TC39: Finished Proposals
Topic: Values that arrive slowly · standards, tools
Lesson 9: fetch
Ajax, named in 2005
Asking a server for data without reloading the page once had a famous name. On 18 February 2005 Jesse James Garrett used the term Ajax in an article titled Ajax: A New Approach to Web Applications. The essay calls the name shorthand for Asynchronous JavaScript + XML, and a fundamental shift in what is possible on the web. fetch is today's way to do that job.
Why it fits here: It answers this topic's question, and places fetch in history: pages that load data without reloading were named Ajax in 2005.
Sources: Wikipedia: Ajax (programming); Jesse James Garrett: Ajax: A New Approach to Web Applications
Topic: Asking a server · history, internet
fetch reaches Node.js
Node.js has fetch too. Its documentation calls it a browser-compatible implementation of the fetch() function, added in version 17.5.0. From version 18.0.0 it no longer needed the --experimental-fetch flag, and from version 21.0.0 it was no longer marked experimental. So the same fetch code can run in a browser and on a server.
Why it fits here: It widens this topic's fetch: the same function now works in Node.js programs, not only in browsers.
Source: Node.js documentation: Globals
Topic: Asking a server · tools, standards
What counts as ok
The ok flag has an exact meaning. The Fetch standard defines an ok status as a status in the range 200 to 299, inclusive, and MDN describes ok as stating whether the response was successful. So a 404 or a 500 gives ok as false, while 200, 201 and 204 all give true. Anything outside that one range fails the check.
Why it fits here: It answers this topic's question: res.ok is true exactly for statuses 200 to 299.
Sources: WHATWG: Fetch Standard; MDN: Response.ok
Topic: Reading the answer before you believe it · standards, numbers
Reading a body twice
A body can be read only once, but a copy can be made first. MDN explains that clone() makes a copy of a response, identical in every way, and that the main reason clone() exists is to allow several uses of a body that can be read only once. The Fetch standard's steps throw a TypeError if clone() is called when the body can no longer be used.
Why it fits here: It gives a way round this topic's read-once rule: clone the response first, then read each copy once.
Sources: MDN: Response.clone(); WHATWG: Fetch Standard
Topic: Reading the answer before you believe it · standards, tricks
JSON that arrives as plain text
A body sent as a string gets a type of its own. The Fetch standard's steps say that when the body is a string, its type is set to text/plain;charset=UTF-8. So JSON sent without a Content-Type header reaches the server labelled as plain text, and a server that reads only JSON may ignore it. That is why the header is set to application/json.
Why it fits here: It explains this topic's Content-Type header: without it, a JSON string is sent labelled as plain text.
Source: WHATWG: Fetch Standard
Topic: Sending data to a server · standards, mistakes
A GET with a body is refused
fetch refuses one combination outright. The Fetch standard's steps say that if a body is given and the method is GET or HEAD, fetch must throw a TypeError. Data for a GET travels in the address instead, as search parameters, which the next topic builds safely with URL.
Why it fits here: It answers this topic's question, and explains why data is sent with POST: fetch will not send a body with GET at all.
Source: WHATWG: Fetch Standard
Topic: Sending data to a server · standards, mistakes
One standard for addresses
Browsers once disagreed about addresses. The WHATWG's URL Standard notes that spaces, other illegal characters, query encoding and equality were concepts not entirely shared, or defined. It sets out to align RFC 3986 and RFC 3987, the older standards for addresses, with what browsers really do, and to obsolete those RFCs in the process. The URL object follows that standard.
Why it fits here: It explains why this topic builds addresses with URL: it follows one standard that browsers now share.
Source: WHATWG: URL Standard
Topic: Building addresses safely · standards, internet
Plus means space
In a query string, a plus sign means a space. MDN warns that the URLSearchParams constructor interprets plus signs as spaces, which might cause problems, and the URL standard's steps say so plainly: replace any + in a name and value with a space. So a value such as +91 must be escaped, as searchParams.set does, or its + is lost.
Why it fits here: It answers this topic's question: in a query string + stands for a space, so set must escape a real plus sign.
Sources: MDN: URLSearchParams; WHATWG: URL Standard
Topic: Building addresses safely · standards, mistakes
Promises that cannot be cancelled
A promise cannot be cancelled. TC39 once had a proposal for cancelable promises, and its repository now calls itself the former home of the now-withdrawn proposal. The DOM standard filled the gap: since promises have no built-in way to abort, AbortController gives APIs such as fetch an abort() method that changes the state of an AbortSignal.
Why it fits here: It answers this topic's question: promises have no cancel button, so a separate signal does the job.
Sources: TC39: proposal-cancelable-promises; WHATWG: DOM Standard
Topic: Time limits and cancelling · standards, history
Two reasons to stop
One request may need two ways to stop: a Cancel button and a time limit. AbortSignal.any() takes several signals and returns one that aborts when any of them aborts, with the reason of the first. MDN shows it working across browsers since March 2024, and the DOM standard defines it.
Why it fits here: It joins this topic's two tools: a cancel by hand and a time limit can be combined into one signal for fetch.
Sources: MDN: AbortSignal.any(); WHATWG: DOM Standard
Topic: Time limits and cancelling · standards, tools
A rule from 1995
The rule that guards this topic began with JavaScript itself. Wikipedia dates the same-origin policy to Netscape Navigator 2.02 in 1995, shortly after JavaScript arrived in Netscape 2.0. The idea of an origin was written down as a standard only in December 2011, in RFC 6454, The Web Origin Concept, by Adam Barth of Google.
Why it fits here: It gives this topic's same-origin rule its history: browsers enforced it from 1995, long before a standard described it.
Sources: Wikipedia: Same-origin policy; RFC 6454: The Web Origin Concept
Topic: Other sites: origins and CORS · history, standards
Why CORS asks permission
CORS works by permission for a reason. The Fetch standard explains that the CORS protocol lets responses declare that they can be shared with other origins. It needs to be an opt-in mechanism, the standard says, to prevent leaking data from responses behind a firewall, such as a company's intranet. A page on the open web must not read pages reachable only from inside an office.
Why it fits here: It answers this topic's question, and explains why the fix is on the server: only the server can give the permission.
Source: WHATWG: Fetch Standard
Topic: Other sites: origins and CORS · standards, privacy
Lesson 10: Maps and sets
Objects as maps, and a known attack
Using a plain object as a lookup table can be dangerous. MDN warns that setting key-value pairs supplied by users on an object may let an attacker override the object's prototype, which can lead to prototype pollution attacks. The weakness has its own entry in MITRE's catalogue, CWE-1321, with Prototype Pollution as its other name. A Map has no prototype keys to reach.
Why it fits here: It answers this topic's question, and gives a security reason for Map: keys typed by people can never reach a prototype.
Sources: MDN: Map; MITRE: CWE-1321
Topic: Map: a table of any key to any value · privacy, standards
Built for keys that come and go
A Map is built for keys that change often. MDN's comparison says a Map performs better where key-value pairs are added and removed often, while an object is not optimized for that. V8's team explains why: if many properties get added to and deleted from an object, keeping track of its shape costs a lot of time and memory, so V8 switches the object to slower properties.
Why it fits here: It gives a speed reason for this topic's Map: a table whose keys keep changing is the job Map was built for.
Sources: MDN: Map; V8 blog: Fast properties in V8
Topic: Map: a table of any key to any value · tools, numbers
JSON has no word for a Map
JSON has no way to write a Map. Its standard, RFC 8259, says JSON can represent four primitive types, strings, numbers, booleans and null, and two structured types, objects and arrays. A Map is neither, so JSON.stringify writes it as an empty object, unless it is first turned into an array of pairs or a plain object.
Why it fits here: It answers this topic's question: JSON knows only objects and arrays, so a Map must be converted before it is written.
Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
Topic: Walking a Map, and moving between forms · standards, mistakes
The way back to an object
Turning a Map into a plain object has a method of its own. MDN describes Object.fromEntries as transforming a list of key-value pairs into an object, and a Map walks as exactly such pairs. The 2019 edition of the standard defines it, and TC39's list of finished proposals names its author, Darien Maillet Valentine.
Why it fits here: It names this topic's way back from a Map to a plain object, ready for JSON.stringify.
Sources: MDN: Object.fromEntries(); ECMAScript 2019 Language Specification; TC39: Finished Proposals
Topic: Walking a Map, and moving between forms · standards, tools
Memo functions, 1968
Remembering answers under their questions has a name, memoization. On 6 April 1968 Donald Michie published "Memo" Functions and Machine Learning in the journal Nature, and Wikipedia traces the word to the Latin memorandum, to be remembered. A cache built with a Map does the same job: it looks up the question before working the answer out again.
Why it fits here: It answers this topic's question, and names its cache: keeping answers under their questions is called memoization.
Sources: Nature: "Memo" Functions and Machine Learning; Wikipedia: Memoization
Topic: Counting, grouping and remembering · history, words
React remembers too
React builds this topic's cache into its components. Its useMemo hook lets a component cache the result of a calculation between re-renders, working it out again only when its inputs change. React's documentation adds that the React Compiler memoizes values and functions automatically, reducing the need for useMemo written by hand.
Why it fits here: It shows this topic's cache in a popular library: React keeps answers between renders, as a Map keeps them between calls.
Source: React: useMemo
Topic: Counting, grouping and remembering · tools, internet
Sets began with Cantor
The idea of a set is younger than it sounds. Wikipedia says set theory, as modern mathematicians understand it, was founded by an 1874 paper of Georg Cantor. The Stanford Encyclopedia of Philosophy dates its birth to late 1873, when Cantor discovered that the points of the real line cannot be counted. JavaScript's Set borrows the name and the main rule: each member once.
Why it fits here: It gives this topic's Set its name and its rule: a collection in which each member appears once, as in mathematics.
Sources: Wikipedia: Set theory; Stanford Encyclopedia of Philosophy: Set Theory
Topic: Set: each value once · maths, history
NaN, once
A Set keeps NaN only once, though NaN is not equal to itself. MDN explains that Map and Set compare with the SameValueZero algorithm, which treats NaN as the same as NaN and otherwise follows ===. It once used SameValue, which kept 0 and −0 apart; the standard's steps now turn a key of −0 into 0 before storing it.
Why it fits here: It answers this topic's question: a Set holds one NaN, and treats 0 and −0 as the same member.
Sources: MDN: Map; ECMAScript Language Specification: CanonicalizeKeyedCollectionKey
Topic: Set: each value once · standards, numbers
Union and friends, since 2024
Comparing two sets once took loops. Set now has methods named after set theory: union, intersection, difference, symmetricDifference, isSubsetOf and more. MDN shows union working in the latest browsers since June 2024, and TC39's list of finished proposals names New Set methods, by Michał Wadas, Sathya Gunasekaran and Kevin Gibbons.
Why it fits here: It answers this topic's question: union, intersection and difference joined JavaScript in 2024.
Sources: MDN: Set.prototype.union(); TC39: Finished Proposals
Topic: Comparing two sets · standards, maths
Circles from Euler to Venn
The pictures used for this topic are older than computers. Wikipedia says the Venn diagram, which shows the logical relation between sets, was popularized by John Venn in the 1880s. The Stanford Encyclopedia of Philosophy traces the line further back: Euler drew circles for terms in the 18th century, and a century later Venn expanded what they could express.
Why it fits here: It gives this topic's union and intersection their classic picture: overlapping circles, drawn since Euler and Venn.
Sources: Wikipedia: Venn diagram; Stanford Encyclopedia of Philosophy: Diagrams
Topic: Comparing two sets · maths, history
Best avoided
JavaScript has a weaker tool still, and its own documentation warns against it. WeakRef, a reference that does not keep its object alive, came with the WeakRefs proposal, whose champions include Dean Tribble and Mark Miller. MDN says correct use of WeakRef takes careful thought and is best avoided if possible, because when, how and whether garbage collection happens is down to each engine.
Why it fits here: It marks the limit of this topic's weak collections: they are safe to use, while WeakRef asks you to predict the garbage collector.
Sources: MDN: WeakRef; TC39: Finished Proposals
Topic: Notes that do not hold on: WeakMap and WeakSet · standards, mistakes
Garbage collection, 1959
The memory clean-up behind this topic is older than JavaScript by decades. Wikipedia credits John McCarthy with inventing garbage collection around 1959, to simplify manual memory management in Lisp: the system, not the programmer, decides which memory to free. MDN adds that all modern JavaScript engines ship a mark-and-sweep collector, which treats an object that cannot be reached as no longer needed.
Why it fits here: It answers this topic's question, and explains what weak notes rely on: memory nobody can reach is freed by itself.
Sources: Wikipedia: Garbage collection (computer science); MDN: Memory management
Topic: Notes that do not hold on: WeakMap and WeakSet · history, tools
No fact matches. Try a shorter word, or take the tag off.