Loading

Fact dictionary

JavaScript

120 facts from 10 lessons of JavaScript. Each one names its source and leads back to its place in the lesson.

Lesson 1: Values and variables

A type named after a person

The boolean, the type of true and false, is named after a person. George Boole was born on 2 November 1815 in Lincoln, England, where his father kept a cobbler's shop. He approached logic in a new way, reducing it to a simple algebra. The data type with only two values carries his name.

Why it fits here: Every yes or no in this topic, such as a tick for a lower berth, is a boolean: a value with only two choices.

Sources: Wikipedia: Boolean data type; MacTutor History of Mathematics: George Boole

Topic: Every value has a type · history, people, maths

The youngest of the eight

The JavaScript standard names eight types today: Undefined, Null, Boolean, String, Symbol, Number, BigInt and Object. The youngest is BigInt. TC39's list of finished proposals places it in ECMAScript 2020, with Daniel Ehrenberg as its champion. It brought whole numbers too high or too low for the number type, so a very long ID number can be held exactly.

Why it fits here: It explains why this topic counts eight types, where books written before 2020 count seven.

Sources: ECMAScript Language Specification; TC39: Finished Proposals; MDN: BigInt

Topic: Every value has a type · standards, history, numbers

A fraction that cost lives

A tiny error in a fraction once cost lives. On 25 February 1991, a Patriot missile battery at Dhahran, Saudi Arabia, failed to track an incoming Scud, which hit an Army barracks and killed 28 Americans. Its clock counted tenths of seconds, and its registers were only 24 bits long, so the time it worked out was slightly off. The error grew the longer the system ran, and it had run for over 100 hours.

Why it fits here: It is this topic's warning made real: a decimal in binary is slightly off, and a slight error repeated becomes a large one.

Source: U.S. GAO: Patriot Missile Defense, Software Problem Led to System Failure at Dhahran (IMTEC-92-26)

Topic: Numbers: one type for every amount · history, numbers, mistakes

When adding 1 does nothing

Numbers have a largest safe whole number, Number.MAX_SAFE_INTEGER, which is 9,00,71,99,25,47,40,991. Past it, whole numbers can no longer all be stored exactly. MDN gives the proof in one line: Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 evaluates to true, which is mathematically incorrect. Two different sums are stored as one and the same number.

Why it fits here: It is why this topic sends very large whole numbers, such as long ID numbers, to BigInt.

Sources: MDN: Number.MAX_SAFE_INTEGER; ECMAScript Language Specification: Number.MAX_SAFE_INTEGER

Topic: Numbers: one type for every amount · numbers, maths

Backticks since 2015

Template literals are younger than many JavaScript habits. They arrived with ECMAScript 2015, the 6th edition of the standard, dated June 2015, which has a section called Template Literals. Before that, text with gaps was built by joining pieces with +, quote by quote. Older code, and older answers online, still build text that way.

Why it fits here: It explains why this topic meets both styles: + joins in older code, and backticks in newer code.

Source: ECMAScript 2015 Language Specification

Topic: Strings: text, written three ways · history, standards

One face, two code units

A string's length is not always the number of characters you see. JavaScript uses UTF-16, where each Unicode character may be encoded as one or two code units, and length counts code units. MDN warns that scripts such as emojis and mathematical symbols need care. So "😀".length is 2: one face, two code units.

Why it fits here: It refines this topic's rule on length: it counts code units, which match the characters for most text, but not for emojis.

Sources: MDN: String length; ECMAScript Language Specification: The String Type

Topic: Strings: text, written three ways · standards, numbers, mistakes

Names in Hindi

JavaScript names are not limited to English letters. MDN explains that identifiers are not limited to ASCII: a name may start with any character in Unicode's ID_Start category, or with _ or $. Unicode lists the Devanagari letters as ID_Start and its vowel signs as ID_Continue, so राशि is a valid name. Whether to use such names is a team's choice; these lessons use English ones.

Why it fits here: It shows that this topic's naming rules are about clarity, not a limit of the language: the language accepts far more than good style.

Sources: MDN: Lexical grammar; Unicode Character Database: DerivedCoreProperties.txt

Topic: Variables: names made with const, let and var · india, standards, languages

let and const since 2015

The jar labels let and const are young. They came with ECMAScript 2015, whose section 13.3.1 is called Let and Const Declarations; before that edition, var made every variable. A name made with let can only be used after the place of its declaration is reached. MDN calls the stretch before it the temporal dead zone.

Why it fits here: It is why this topic prefers const and let: they are the newer way, and var stays for old code.

Sources: ECMAScript 2015 Language Specification; MDN: let

Topic: Variables: names made with const, let and var · history, standards

When += was =+

The shortcut += once had its sign the other way round. Dennis Ritchie's history of C tells how B introduced generalized assignment operators, written x=+y to add y to x. In B and early C the operator was spelled =+, and Ritchie calls that a mistake, repaired in 1976. The fix put the sign first, as += is written in C and in JavaScript today.

Why it fits here: It shows that this topic's shortcuts are older than JavaScript: they came down from B and C.

Source: Dennis M. Ritchie: The Development of the C Language

Topic: Changing a value · history, people

Who invented ++

The ++ and -- operators have a known inventor. Ken Thompson created the B language in 1969 and 1970, and Ritchie writes that Thompson went a step further by inventing the ++ and -- operators. Their place, before or after the name, decides whether the change happens before or after the value is noted. That is why this topic keeps them on a line of their own.

Why it fits here: Since the two places differ, a ++ inside a longer line is easy to misread; on a line of its own, both mean the same.

Source: Dennis M. Ritchie: The Development of the C Language

Topic: Changing a value · history, people, tricks

Nothing becomes zero

One conversion surprises nearly everyone. MDN notes that empty or whitespace-only strings are converted to 0, and the standard agrees: a string of only white space has the value +0. So Number("") and Number(" ") both give 0, not NaN. An empty box on a form can turn into a real zero in a sum, so test for an empty string first when empty should mean missing.

Why it fits here: It is a trap of this topic's conversions: an empty input is not NaN, so a missing price can quietly count as zero.

Sources: MDN: Number; ECMAScript Language Specification

Topic: Turning one type into another · mistakes, numbers

Two nothings, two numbers

The two kinds of nothing convert differently. MDN's list of number conversions says that undefined turns into NaN, while null turns into 0. The standard's own ToNumber steps agree: if the value is undefined, return NaN; if it is null or false, return +0. So a sum with a missing value can give NaN or a quiet zero, depending on which nothing it met.

Why it fits here: It joins two ideas of this lesson: null and undefined differ in meaning, and also in what they become as numbers.

Sources: MDN: Number; ECMAScript Language Specification: ToNumber

Topic: Turning one type into another · standards, mistakes

Lesson 2: Operators and conditionals

Three ways to ask equal

JavaScript has three ways to ask whether two values are the same. MDN lists them: === for strict equality, == for loose equality, which converts types first, and Object.is(). The last differs from === in two corners: Object.is(NaN, NaN) is true, and Object.is(-0, 0) is false. Most code needs only ===.

Why it fits here: It places this topic's rule in context: === is the everyday choice, == is avoided, and Object.is is kept for rare corners.

Sources: MDN: Equality comparisons and sameness; MDN: Object.is(); ECMAScript Language Specification: Object.is

Topic: Comparing values · standards, maths

Capitals first

Every capital letter sorts before every small one, so "Zebra" < "apple" is true. Strings are compared by their UTF-16 code units, and in those codes the capitals come first. The order goes back to ASCII, first published in 1963, whose designers put the small letters in later columns, so that a letter's two cases differ by a single bit.

Why it fits here: It is why this topic converts text before comparing: by codes, "Zebra" comes before "apple", and "10" before "9".

Sources: MDN: Less than (&lt;); Wikipedia: ASCII

Topic: Comparing values · history, standards, words

Laws from a man born in Madurai

Two rules for turning questions around carry the name of a man born in India. Augustus De Morgan was born on 27 June 1806 in Madura, now Madurai in Tamil Nadu, and became the first professor of mathematics at University College London. De Morgan's laws say that not (a and b) means (not a) or (not b). In JavaScript, !(a && b) equals !a || !b.

Why it fits here: It gives this topic a tool: to turn a joined question around, flip each part and swap && with ||.

Sources: MacTutor History of Mathematics: Augustus De Morgan; Wikipedia: De Morgan's laws

Topic: And, or, not: joining questions · india, maths, people

Why && has two signs

The && and || signs were added on purpose. In B, the language before C, a single & and | did this job, with a special meaning inside if statements that was difficult to explain and use. Dennis Ritchie writes that, at the suggestion of Alan Snyder, he introduced && and || to make the mechanism more explicit. JavaScript writes them the same way.

Why it fits here: It explains this topic's stopping rule: && and || were made for exactly this, to stop as soon as the answer is known.

Source: Dennis M. Ritchie: The Development of the C Language

Topic: And, or, not: joining questions · history, people

The one falsy object

There is one falsy object, and it exists for old websites. MDN notes that the only falsy object in JavaScript is the built-in document.all. The standard makes room for it: objects with a special [[IsHTMLDDA]] slot behave like undefined when turned into a boolean. Its note says that document.all has this slot and exists for web compatibility purposes.

Why it fits here: It is the single exception to this topic's rule that every object is truthy, kept so that very old pages still work.

Sources: MDN Glossary: Falsy; ECMAScript Language Specification: The [[IsHTMLDDA]] Internal Slot

Topic: Truthy and falsy: what counts as yes · history, browsers, standards

A young operator for real zeros

The ?? operator is young. TC39's list of finished proposals places nullish coalescing in ECMAScript 2020, with Gabriel Isenberg as its champion, and MDN marks it as working across browsers since July 2020. It returns its right side only when the left side is null or undefined, so a real 0 or an empty string survives.

Why it fits here: It is the tool this topic offers for real zeros: || replaces every falsy value, while ?? replaces only the two kinds of nothing.

Sources: TC39: Finished Proposals; MDN: Nullish coalescing operator (??)

Topic: Truthy and falsy: what counts as yes · standards, history

Two lines that broke a lock

Missing braces once broke a security check. In February 2014, Adam Langley described a bug in Apple's code for secure connections: two goto fail lines in a row under one if. The first was bound to the if, but the second, despite the indentation, was not conditional at all. The code always jumped past the check, so the signature verification never failed.

Why it fits here: It is the reason for this topic's rule to always write braces: indentation shows what a person meant, braces what the machine does.

Source: ImperialViolet (Adam Langley): Apple's SSL/TLS bug

Topic: Making a choice with if · history, mistakes, privacy

There is no else if

JavaScript has no else if keyword. MDN notes that there is no elseif, in one word, in the language: an else if is an else whose one statement happens to be another if. The standard's grammar for an if statement has only if, a condition, a statement, else and a statement. So a chain of else if is a ladder of ifs, each tried only when every one above it was false.

Why it fits here: It explains this topic's rule that the first true question wins: each later if lives inside the else of the one before.

Sources: MDN: if...else; ECMAScript Language Specification: The if Statement

Topic: Making a choice with if · standards, words

The only three-part operator

Every other JavaScript operator works on one value or two. The ternary is the only JavaScript operator that takes three operands: a condition, then a question mark and a value for yes, then a colon and a value for no. The standard's grammar spells the shape out as a short-circuit expression, a question mark, an expression, a colon and another expression.

Why it fits here: It explains the name of this topic's operator: it is the one that takes three parts, which is why it can choose between two values.

Sources: MDN: Conditional (ternary) operator; ECMAScript Language Specification: Conditional Operator

Topic: Choosing a value: the ternary operator · standards, words

Older than C

Choosing a value with a condition is older than C and JavaScript. The construct first appeared in CPL in 1963, written a → b, c, with an arrow for the question and a comma between the two answers. Many languages since have their own spelling, often if a then b else c. JavaScript uses the question mark and colon of the C family.

Why it fits here: It shows that this topic's operator answers an old need: picking a value, rather than running steps, by a condition.

Sources: Wikipedia: Ternary conditional operator; MDN: Conditional (ternary) operator

Topic: Choosing a value: the ternary operator · history, languages

Pride and revulsion

Fall-through has a famous trick. In November 1983, Tom Duff, then working for Lucasfilm, mailed a way of unrolling a loop by interleaving a do-while loop and a switch statement, so that the switch falls into the middle of the loop. He wrote: "Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this discovery."

Why it fits here: It shows how much fall-through can do, and why this topic asks for a break after every case that should stop.

Sources: Wikipedia: Duff's device; Tom Duff's message of 1983 (copy kept by Russ Cox)

Topic: Choosing a path: switch · history, people, tricks

A default anywhere

The default of a switch does not have to come last. MDN notes that by convention the default clause is the last one, but it does not need to be so. The standard's grammar allows case clauses both before and after the default. When no case matches, the switch moves to the default wherever it stands and runs the statements that follow it. From there it falls through, like any other case, until a break.

Why it fits here: It is one more reason for this topic's break in every case: an early default would otherwise run on into the cases below it.

Sources: MDN: switch; ECMAScript Language Specification: The switch Statement

Topic: Choosing a path: switch · standards, mistakes

Lesson 3: Functions

A word for a job

The word function began as an ordinary word for a job. In August 1673, Leibniz wrote of lines that, in a given figure, perform some function, using the word in its usual sense. In 1748, Euler's Introductio in analysin infinitorum brought the function concept to prominence in mathematics. A JavaScript function keeps both sides: a job to do, and an answer worked out from its inputs.

Why it fits here: It matches this topic's picture: a function is a job written once, which can also hand an answer back.

Sources: MacTutor History of Mathematics: The function concept; Wikipedia: Function (mathematics)

Topic: Writing a job once: declaring and calling · history, maths, words

Don't Repeat Yourself

Writing each rule once has a famous name: Don't Repeat Yourself, or DRY. Andy Hunt and Dave Thomas stated it in their book The Pragmatic Programmer: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. They apply it broadly, from code to test plans and even documentation. A function is the everyday tool for it.

Why it fits here: It is the reason this topic writes each rule once as a function: change the rule in one place, and every caller follows.

Sources: The Pragmatic Programmer: tips; Wikipedia: Don't repeat yourself

Topic: Writing a job once: declaring and calling · books, people, tricks

Defaults fill only undefined

A default value fills a gap only when the gap is undefined. MDN says default parameters are used if no value or undefined is passed, and the standard's steps agree: the default is worked out only when the value is undefined. So greet(null) does not get "Guest". The null is passed in as a real value, and the greeting says Hello, null.

Why it fits here: It sharpens this topic's rule on defaults: an empty gap gets the default, but a null is a value, and it is used as given.

Sources: MDN: Default parameters; ECMAScript Language Specification: IteratorBindingInitialization

Topic: Values going in: parameters · standards, mistakes

The hidden arguments object

Extra values are not lost. Inside any ordinary function, arguments is an array-like object that holds every value passed in, even values with no parameter to catch them. MDN now advises that in modern code rest parameters should be preferred. Arrow functions have no arguments object of their own at all.

Why it fits here: It explains what happens to this topic's extra arguments: they are only unnamed, and arguments can still reach them.

Sources: MDN: The arguments object; ECMAScript Language Specification: Arrow Function Definitions

Topic: Values going in: parameters · history, standards

A return that returns nothing

A return and its value must share a line. The standard's grammar forbids a line break between the return keyword and the expression to be returned. If the value starts on the next line, automatic semicolon insertion turns the first line into return; on its own. MDN spells out the result: the function returns undefined, and the expression below is never evaluated.

Why it fits here: It is the reason for this topic's rule to keep the value on the same line as return.

Sources: ECMAScript Language Specification: Rules of Automatic Semicolon Insertion; MDN: return

Topic: Values coming out: return · standards, mistakes

The undefined after console.log

In the Console, console.log("hi") prints hi and then the word undefined. Chrome's guide explains why: the Console is a REPL, which reads your code, evaluates it, prints the result of your expression and loops. MDN lists console.log's return value as none, undefined. So the first line is what the function showed, and the second is what it gave back.

Why it fits here: It shows this topic's difference between showing and returning in one place: console.log shows a value but gives back nothing.

Sources: Chrome for Developers: Run JavaScript in the Console; MDN: console.log(); ECMAScript Language Specification: The return Statement

Topic: Values coming out: return · tools, mistakes

An object that can be called

Functions are objects, yet typeof gives them a type name of their own. The standard's steps for typeof say: if the value has a [[Call]] internal method, return "function"; otherwise, for an object, return "object". So a function is an object that can be called, and typeof picks out exactly that one ability.

Why it fits here: It explains this topic's opening claim: a function is a value, an object with one extra power, the power to be called.

Source: ECMAScript Language Specification: The typeof Operator

Topic: Functions as values: expressions and arrows · standards

What arrows leave out

Arrow functions are not only shorter. The standard notes that an arrow function does not define its own bindings for arguments, super, this or new.target; inside it, those words mean what they mean in the code around it. MDN puts it the same way, and adds that arrow functions should not be used as methods, and cannot be used as constructors.

Why it fits here: It adds a warning to this topic's arrows: they suit short jobs and callbacks, but not methods that need their own this.

Sources: ECMAScript Language Specification: Arrow Function Definitions; MDN: Arrow function expressions

Topic: Functions as values: expressions and arrows · standards, mistakes

Don't call us, we'll call you

Callbacks turn the usual order round: your code does not call the library; the library calls your code. Martin Fowler calls this inversion of control, also known as the Hollywood Principle: don't call us, we'll call you. He traces the colourful name to a 1983 paper by Richard Sweet on Mesa, which lists it among its design goals.

Why it fits here: It names what this topic's callbacks do: you hand over a function, and the browser or the array calls it when the time comes.

Source: Martin Fowler: InversionOfControl

Topic: Functions passed to functions: callbacks · history, people, words

Zero is never quite now

A browser keeps its own rules for when to call back. The HTML standard says that once timers are nested more than five deep, a timeout of less than 4 milliseconds becomes 4. MDN describes the effect: after a nested setTimeout has been scheduled 5 times, browsers enforce a minimum of 4 milliseconds. So a delay of 0 never quite means now.

Why it fits here: It is a reminder from this topic: a callback runs when its caller decides, and the caller may be the browser, with its own clock.

Sources: WHATWG: HTML Standard, Timers; MDN: setTimeout()

Topic: Functions passed to functions: callbacks · standards, numbers, browsers

The operational cellar

The stack has inventors. Klaus Samelson and Friedrich L. Bauer of the Technical University of Munich proposed a stack, which they called Operationskeller, the operational cellar, in 1955, and filed a patent in 1957. In 1988 Bauer received the IEEE Computer Pioneer Award, whose citation reads: For computer stacks.

Why it fits here: Every call in this topic is pushed onto such a stack and taken off again, newest first.

Sources: Wikipedia: Stack (abstract data type); IEEE Computer Society: Friedrich L. Bauer

Topic: Functions calling functions: the call stack · history, people, machines

Calls that reuse their frame

Some recursion need not grow the stack. ECMAScript 6 added Proper Tail Calls: a call made in tail position reuses the stack space of the calling function, instead of adding a new frame. When WebKit described its version in May 2016, it noted that for deeply recursive code, PTC enables code to run that would otherwise throw a stack overflow exception.

Why it fits here: It explains why the stack in this topic can overflow: each ordinary call adds a frame, and only special tail calls can reuse one.

Source: WebKit: ECMAScript 6 Proper Tail Calls in WebKit

Topic: Functions calling functions: the call stack · standards, machines

Lesson 4: Scope

Two kinds of global

Not all global names are alike. In a script, a variable declared with var at the top level is added as a property of the global object, window in a browser. A let or a const at the top level is not: MDN notes that let declarations do not create properties on globalThis. Both kinds are still global, shared by every script on the page.

Why it fits here: It refines this topic's global scope: let and const at the top level are global names, but they stay off the window object.

Sources: MDN: var; MDN: let; ECMAScript Language Specification: Global Environment Records

Topic: What scope is · standards, browsers

Global here, local there

The same line can be global in one place and local in another. In browsers, the top-level scope has traditionally been the global scope, so var something makes a new global, except within modules. Node.js's own documentation says that in Node this is different: the top-level scope is not the global scope, and var something stays local to its module.

Why it fits here: It shows that this topic's global scope depends on where the code runs: a browser script shares it, a Node module keeps its own.

Source: Node.js documentation: Global objects

Topic: What scope is · tools, standards

A fresh record for every call

Behind every call is a record the standard calls an execution context: a specification device that is used to track the runtime evaluation of code. At any moment, at most one execution context is actually running code. Each call of a function starts with a new one, so its names are its own, and they are gone when it returns.

Why it fits here: It explains this topic's fresh set of names: each call has its own record, made when it starts and dropped when it returns.

Sources: ECMAScript Language Specification: Execution Contexts; ECMAScript Language Specification: PrepareForOrdinaryCall

Topic: Names inside a function · standards, machines

Known before its line

A var is known before its line runs. MDN explains that var declarations, wherever they occur in a script, are processed before any code within the script is executed, so a var anywhere acts as if declared at the top. Until its assignment is reached, the variable remains undefined. This behaviour is called hoisting.

Why it fits here: It explains why this topic says var belongs to the whole function body: the name exists from the first line, though its value comes later.

Sources: MDN: var; ECMAScript Language Specification: Variable Statement

Topic: Names inside a function · standards, mistakes

A new let for every round

A loop treats let specially. MDN explains that when a for loop starts with a let declaration, a new lexical scope is created each time round, with new variables that take their values from the last iteration. The standard names the step CreatePerIterationEnvironment. Closures show it: functions made in different rounds each keep their own copy, not one shared variable.

Why it fits here: It adds a twist to this topic's block rule: a loop's braces make a fresh block, with fresh let names, on every round.

Sources: MDN: for; ECMAScript Language Specification: The for Statement

Topic: Names inside a block · standards, tricks

The compound statement

Braces do more than mark scope. MDN notes that the block statement is often called the compound statement in other languages: it lets you use several statements where JavaScript expects only one. That is how an if, which takes one statement, can run many lines. A block can even stand alone, braces with no if, to keep a helper name short-lived.

Why it fits here: It joins this topic to the if lessons: the braces that hold an if's lines are the same blocks that limit let and const.

Sources: MDN: Block statement; ECMAScript Language Specification: The if Statement

Topic: Names inside a block · standards, words

The statement that bent the chain

One old statement made the chain hard to follow. The with statement extends the scope chain for a statement, so a plain name inside it could mean a property of an object or a variable, depending on the object. MDN says its use is not recommended, as it may be the source of confusing bugs and makes optimization impossible, and it is forbidden in strict mode.

Why it fits here: It shows why this topic's lookup rule matters: when the chain is fixed by where code is written, a name can be found by reading.

Sources: MDN: with; ECMAScript Language Specification: The with Statement

Topic: Scopes inside scopes · standards, mistakes, history

Scope by the shape of the code

Finding names by where code is written is called lexical scope, and it was once a new idea. The original Lisp interpreter of 1960 used dynamic scope, which looks a name up by the calls running at the time. Scheme, from Guy Steele and Gerald Sussman at the MIT AI Laboratory, was the first dialect of Lisp to choose lexical scope.

Why it fits here: It names the rule of this topic: the chain of scopes follows the shape of the code as written, not the order of the calls.

Sources: Wikipedia: Scope (computer science); Wikipedia: Scheme (programming language); Scheme research: The Lambda Papers

Topic: Scopes inside scopes · history, people, languages

Scheme-ish functions

JavaScript's closures come from a deliberate choice. Brendan Eich has written that he was recruited to Netscape with the promise of doing Scheme in the browser. Looking back in 2008, he wrote that he was happy he chose Scheme-ish first-class functions and Self-ish prototypes as the main ingredients. First-class functions with lexical scope are what make closures.

Why it fits here: It shows that this topic's closures are no accident of JavaScript: they came with the Scheme-style functions it was built on.

Source: Brendan Eich: Popularity

Topic: Closures: functions that remember · history, people, languages

Private before the hash

For years, closures were JavaScript's way to keep a value private. MDN explains that JavaScript, prior to classes, didn't have a native way of declaring private methods, and that closures could emulate them. ECMAScript 2022 gave classes a # prefix for private elements, and MDN notes that closures can emulate it, but cannot compare to the # syntax in ergonomics.

Why it fits here: It shows what this topic's private memory is for: a count that no code outside the closure can change.

Sources: MDN: Closures; MDN: Private elements; ECMAScript 2022 Language Specification

Topic: Closures: functions that remember · history, standards

The name that broke websites

Even the name for the global object was hard to choose. A proposal for one name that works in every environment first tried the name global, but shipping it broke some existing websites, which already used that name for their own purposes. After gathering data on a short list of choices, the proposal settled on globalThis, a name highly likely to be web compatible.

Why it fits here: It is this topic's danger at the scale of the web: global names already in use can block even the language's own new names.

Source: TC39: proposal-global

Topic: Keeping global names few · history, standards, words

Modules are strict from the start

A misspelt name in an assignment is a classic way to make a global by accident. MDN explains that in sloppy mode, mistyping a variable in an assignment creates a new property on the global object and the code goes on as if it worked. Strict mode turns that into an error. In a module it needs no switch: module code is always strict mode code.

Why it fits here: It shows the safest home for this topic's rule: in a module, an undeclared assignment fails at once instead of quietly making a global.

Sources: MDN: Strict mode; ECMAScript Language Specification: Strict Mode Code

Topic: Keeping global names few · standards, mistakes

Lesson 5: Arrays

An object underneath

An array is an object underneath. The standard calls it an exotic object that gives special treatment to array index property keys, the 0, 1 and 2 of its items. That is why typeof [] says object, the same as for any object. It is also why Array.isArray exists: typeof alone cannot tell an array from other objects.

Why it fits here: It explains this topic's last tool: Array.isArray is needed because, to typeof, every array looks like any other object.

Sources: ECMAScript Language Specification: Array Exotic Objects; MDN: typeof

Topic: Making an array, and reading it · standards

The longest list

An array cannot grow for ever. MDN explains that its length is an unsigned, 32-bit integer, so an array holds at most 4,29,49,67,295 items. Its own example sets a length of 232, which is 4,29,49,67,296, and gets a RangeError: Invalid array length. Memory runs out long before that, so the limit lives mostly in the standard.

Why it fits here: It puts a number on this topic's length: a count kept in 32 bits, which is far more than any page will need.

Sources: MDN: Array length; ECMAScript Language Specification: Array Exotic Objects

Topic: Making an array, and reading it · numbers, standards

A sailor's word

The method splice is named after a sailor's craft. Rope splicing is the forming of a semi-permanent joint between two ropes, or two parts of one rope, by partly untwisting and then interweaving their strands. The method does the same to an array: it opens the list at a place, takes some items out and weaves new ones in.

Why it fits here: It gives this topic's hardest method a picture to remember: splice opens the list, removes strands and weaves in new ones.

Sources: Wikipedia: Rope splicing; Wiktionary: splice

Topic: Changing an array · words, real life

A twin that leaves the list alone

Changing an array in place can surprise the code that shares it, so splice now has a twin. The method toSpliced() is the copying version of the splice() method: it returns a new array with some elements removed or replaced, and the original stays as it was. MDN shows it working across browsers since July 2023.

Why it fits here: It gives this topic's changes a safer form: when other code shares the array, change a copy instead of the list itself.

Sources: MDN: Array.prototype.toSpliced(); ECMAScript Language Specification: Array.prototype.toSpliced

Topic: Changing an array · standards, history

Two searches, one disagreement

The methods includes and indexOf can disagree about one value. MDN explains that includes compares items using the SameValueZero algorithm, which works like === except that NaN is considered equal to itself. The method indexOf uses strict equality, so it always returns -1 when looking for NaN. So [1, 2, NaN].includes(NaN) is true, while indexOf cannot find NaN at all.

Why it fits here: It shows why this topic offers both methods: includes answers yes or no reliably, even for NaN, while indexOf gives a position.

Sources: MDN: Array.prototype.includes(); MDN: Array.prototype.indexOf(); ECMAScript Language Specification: Keyed Collections

Topic: Finding items · standards, mistakes

A faster way to ask is it there

For a list you search often, a Set is faster than an array. The standard requires Set objects to give access times that are sublinear on the number of elements, so a lookup does not check every item in turn. MDN notes that Set's has method is, on average, faster than Array.prototype.includes when both hold the same number of items.

Why it fits here: It adds a next step to this topic: includes checks items one by one, so a long list searched again and again belongs in a Set.

Sources: ECMAScript Language Specification: Set Objects; MDN: Set

Topic: Finding items · standards, numbers

The method that broke the web

Naming an array method can break old websites. In 2018, a method called Array.prototype.flatten turned out to be web-incompatible: shipping it in Firefox Nightly broke at least one popular website, because the widespread MooTools library used the same name. The proposal's author jokingly suggested smoosh as a new name. In the end, flatten was renamed to flat.

Why it fits here: It shows what this topic's array methods carry: every new name must avoid the names that old pages already gave arrays.

Source: Chrome for Developers: #SmooshGate FAQ

Topic: Taking parts, joining, and turning into text · history, browsers, words

Arrays turn into commas

An array turned into text gets commas. The standard's toString for arrays just calls join, and join, when no separator is given, separates the items with a comma. So `${[1, 2, 3]}` gives 1,2,3, the same as [1, 2, 3].join(). To get spaces or anything else, call join yourself with the separator you want.

Why it fits here: It explains a surprise around this topic's join: an array placed in a template literal arrives with commas and no spaces.

Sources: ECMAScript Language Specification: Array.prototype.toString; MDN: Array.prototype.join()

Topic: Taking parts, joining, and turning into text · standards, mistakes

A copy all the way down

Copying with slice() makes a new outer array, but the objects inside are still shared. For a full copy, browsers have offered structuredClone() across the board since March 2022. MDN explains that it creates a deep clone of a value using the structured clone algorithm, so nested arrays and objects are copied too, and the copy shares nothing with the original.

Why it fits here: It finishes this topic's lesson on sharing: slice() copies one level, while structuredClone() copies every level.

Sources: MDN: structuredClone(); WHATWG: HTML Standard, Structured data

Topic: Two names, one array · standards, tools

Freezing, one level deep

A const keeps the name fixed, not the items, but an array can be frozen. MDN explains that freezing an object prevents extensions and makes existing properties non-writable, so a frozen array's items cannot be changed, added or removed. It also warns that the freeze is shallow: arrays and objects inside a frozen array can still change.

Why it fits here: It answers this topic's question about const: when the items themselves must not change, freeze the array.

Sources: MDN: Object.freeze(); ECMAScript Language Specification: Object.freeze

Topic: Two names, one array · standards, mistakes

Stable since Chrome 70

Sorting is stable now: items that compare as equal keep their original order. The standard says so in plain terms, i.e., the sort is stable. It was not always so in Chrome. V8's team describes moving to a stable algorithm and making sort stable in V8 v7.0, Chrome 70. So you can sort by name and then by date, and items with the same date stay in name order.

Why it fits here: It makes this topic's compare function safer to chain: sort by one key, then another, and equal items keep the first order.

Sources: ECMAScript Language Specification: SortIndexedProperties; V8: Getting things sorted in V8

Topic: Putting an array in order · standards, browsers, history

A sort from Python

Chrome sorts arrays with an algorithm borrowed from another language. V8's team chose Timsort, initially developed by Tim Peters for Python in 2002, and describes it as an adaptive stable Mergesort variant. It looks for so-called runs, stretches of the list that are already in order, which real lists often have, such as marks entered in roughly rising order.

Why it fits here: It shows what runs behind this topic's sort: one well-studied algorithm, shared by languages, doing the comparing you supply.

Source: V8: Getting things sorted in V8

Topic: Putting an array in order · history, people, languages

Lesson 6: Loops

Why the counter is called i

Loop counters are often called i, j and k, and the habit is older than JavaScript. In early Fortran there were no type declarations: variables whose name starts with I, J, K, L, M or N were whole numbers, and all others decimals. Fortran's own guide still notes that, without implicit none, variables are typed by the letter they begin with.

Why it fits here: It gives this topic's counter a history: in Fortran, a name starting with i was a whole number, just right for counting.

Sources: Wikipedia: Fortran; Fortran-lang: Variables

Topic: The for loop · history, languages, words

A loop with nothing in its head

Every part of a for loop's head is optional. MDN notes that all three expressions in the head of the for loop are optional, and the standard's grammar marks each one as optional. So for (;;) is a legal loop with no start, no condition and no step. It runs until a break inside it stops it.

Why it fits here: It shows what this topic's condition does: leave it out, and nothing ever tells the loop to stop.

Sources: MDN: for; ECMAScript Language Specification: The for Statement

Topic: The for loop · standards, tricks

No program can check every loop

No tool can check every loop for you. Alan Turing proved in 1937 that the halting problem is undecidable: no general algorithm can correctly decide, for every program and input, whether it finishes or runs forever. Simple cases are easy to decide, but more complex programs are not. Making sure that a loop ends stays the programmer's own job.

Why it fits here: It is why this topic insists that something inside the loop must move the condition towards false: no tool can promise it for you.

Sources: Wikipedia: Halting problem; Stanford Encyclopedia of Philosophy: Turing Machines

Topic: while: repeating until something changes · history, people, maths

A loop nobody can prove will stop

Here is a while loop nobody can prove always stops. Start with any whole number; if it is even, halve it, and if it is odd, triple it and add one; repeat until you reach 1. Lothar Collatz introduced the idea in 1937. Computers have checked every starting value up to 271, and all reach 1, but no proof exists.

Why it fits here: It shows why this topic's warning is serious: whether a loop ends can be a question that even mathematicians cannot answer.

Sources: Wikipedia: Collatz conjecture; OEIS: A006577

Topic: while: repeating until something changes · maths, people, numbers

Names, not items

The for...in loop walks property names, and it has two surprises for arrays. MDN explains that it iterates over all enumerable string properties of an object, so for an array it gives the indexes as strings, "0", "1" and "2". And the standard says the mechanics and order of enumerating the properties is not specified, beyond a set of rules. For arrays, for...of is the safer loop.

Why it fits here: It explains this topic's warning not to confuse the two: for...in is built for an object's names, for...of for a list's items.

Sources: MDN: for...in; ECMAScript Language Specification: EnumerateObjectProperties

Topic: for...of: every item, one by one · standards, mistakes

Not only for arrays

A for...of loop walks far more than arrays. MDN lists the iterable objects it accepts: Array, String, TypedArray, Map, Set, NodeList and other DOM collections, the arguments object, generators and user-defined iterables. So the NodeList that document.querySelectorAll gives back can be walked with for...of, item by item, with no counter at all.

Why it fits here: It widens this topic's loop: anything that can be listed, from the letters of a string to the elements of a page, can be walked the same way.

Sources: MDN: for...of; WHATWG: DOM Standard, NodeList

Topic: for...of: every item, one by one · standards, tools

A break that leaves two loops

A break can leave more than one loop. MDN explains that a labeled statement is any statement prefixed with an identifier, and that you can jump to the label with a break or continue nested within it. So outer: for (...) { for (...) { break outer; } } ends both loops at once. Labels are rare in everyday code, but they solve this one problem neatly.

Why it fits here: It adds one tool to this topic's break, which on its own ends only the innermost loop.

Sources: MDN: Labeled statement; ECMAScript Language Specification: Labelled Statements

Topic: break, continue, and loops inside loops · standards, tricks

A notation from 1894

How fast a loop's work grows has a notation older than computers. The symbol O was first introduced by the number theorist Paul Bachmann in 1894, and MacTutor calls him best known for his work in analytic number theory and for introducing the O-notation. Today a loop inside a loop over n items is called O(n2): double the list, and the work grows four times.

Why it fits here: It puts a name on this topic's warning that nested loops multiply: n rounds inside n rounds is n times n.

Sources: Wikipedia: Big O notation; MacTutor History of Mathematics: Paul Bachmann

Topic: break, continue, and loops inside loops · history, maths, people

Where Math.max starts

The standard's own Math.max shows a safe starting point. Its steps begin with a largest value of minus infinity, then compare every argument with it in turn. So Math.max() with nothing to compare returns -Infinity, the starting value itself. Starting from 0 instead would give a wrong answer for a list of losses, where every number is negative.

Why it fits here: It is the reason for this topic's rule on largest values: start from something no real value can lose to, such as the first item.

Source: ECMAScript Language Specification: Math.max

Topic: The patterns loops are used for · standards, maths

Twenty accumulators

The word accumulator comes from early machines. ENIAC, built in the 1940s, was a large, modular computer, and twenty of its modules were accumulators that could add, subtract, and hold a ten-digit decimal number in memory. The University of Pennsylvania's account lists those twenty accumulators among the machine's memory. A loop's running total keeps the name and does the same job.

Why it fits here: It explains the name of this topic's running total: an accumulator gathers a result, round by round, as ENIAC's did.

Sources: Wikipedia: ENIAC; Penn Engineering: ENIAC

Topic: The patterns loops are used for · history, machines

Map and reduce at Google's scale

The names map and reduce grew far beyond arrays. In 2004, Jeffrey Dean and Sanjay Ghemawat of Google described MapReduce, a programming model for processing and generating large data sets. They wrote that their abstraction was inspired by the map and reduce primitives present in Lisp and many other functional languages. The same two ideas sit in every JavaScript array.

Why it fits here: It shows how far this topic's methods reach: the same map and reduce that tidy one array also process data across many machines.

Sources: Google Research: MapReduce, Simplified Data Processing on Large Clusters; MapReduce paper (OSDI 2004)

Topic: Loops as methods: forEach, map, filter, reduce · history, people, tools

The empty-list trap

The method reduce has one trap on empty lists. MDN lists a TypeError, thrown if the array contains no elements and no initial value is provided, and the standard's steps say the same. So [].reduce((a, b) => a + b) fails, while [].reduce((a, b) => a + b, 0) gives 0. A starting value makes the method safe.

Why it fits here: It is the reason this topic always passes reduce a starting value: with one, an empty list gives a sensible answer.

Sources: MDN: Array.prototype.reduce(); ECMAScript Language Specification: Array.prototype.reduce

Topic: Loops as methods: forEach, map, filter, reduce · standards, mistakes

Lesson 7: Objects

Numbers first, then the rest

An object's keys come back in an order the standard fixes. Keys that look like array indexes come first, in ascending numeric order; the other string keys follow in the order they were created. So an object made as { b: 1, 2: 1, a: 1, 1: 1 } lists its keys as 1, 2, b, a. Order of writing is kept only for ordinary names.

Why it fits here: It explains a surprise when this topic's objects are printed: number-like keys jump to the front, in number order.

Source: ECMAScript Language Specification: OrdinaryOwnPropertyKeys

Topic: Making an object, and reading it · standards, mistakes

Every key is text

An object's keys are always text, or symbols. MDN puts it plainly: the keys of an Object must be either a String or a Symbol, while a Map's keys can be any value. So obj[1] and obj["1"] read the very same property: the number is turned into the string "1" first. The standard's ToPropertyKey step does that turning.

Why it fits here: It explains this topic's brackets: whatever goes inside them becomes a text key, so 1 and "1" name one property.

Sources: MDN: Map; ECMAScript Language Specification: ToPropertyKey

Topic: Making an object, and reading it · standards, words

A safer way to ask own or not

Asking whether an object has a property of its own has a newer, safer form. MDN recommends Object.hasOwn() over Object.prototype.hasOwnProperty(), because it works for null-prototype objects and with objects that have overridden the inherited hasOwnProperty() method. The standard lists it as Object.hasOwn ( obj, key ). The older way still works on everyday objects.

Why it fits here: It adds a careful tool to this topic's in operator: in also finds inherited keys, while Object.hasOwn looks only at the object's own.

Sources: MDN: Object.hasOwn(); ECMAScript Language Specification: Object.hasOwn

Topic: Adding, changing and deleting properties · standards, tools

delete is not a dustbin

The word delete suggests clearing memory, but it does not. MDN notes that, unlike what common belief suggests, perhaps from languages like C++, the delete operator has nothing to do with directly freeing memory. It only removes a property from an object. Memory is managed indirectly, by breaking references: a value that nothing points to any more can be cleared away.

Why it fits here: It sharpens this topic's delete: it removes a label from an object, and the value goes only when nothing else holds it.

Sources: MDN: delete; ECMAScript Language Specification: OrdinaryDelete

Topic: Adding, changing and deleting properties · mistakes, languages

Two equal-looking objects are not equal

Two objects with the same contents are still two objects. MDN states the rule for ===: if both operands are objects, it returns true only if they refer to the same object. So { a: 1 } === { a: 1 } is false, while a === b is true after b = a. Comparing two objects by their contents needs code that checks each property.

Why it fits here: It is this topic's sharing rule seen from the other side: === asks whether two names hold one object, not whether two objects look alike.

Sources: MDN: Strict equality (===); ECMAScript Language Specification: SameValueNonNumber

Topic: Two names, one object, and copies · standards, mistakes

What a deep copy cannot copy

Even structuredClone has limits. MDN explains that function objects cannot be duplicated by the structured clone algorithm; trying throws a DataCloneError, and so does cloning DOM nodes. The HTML standard's steps say the same: if the value is callable, throw a DataCloneError. An object with methods loses nothing to sharing, but it cannot be deep-copied whole.

Why it fits here: It adds a warning to this topic's deep copies: they suit plain data, such as a student's marks, not objects that carry methods.

Sources: MDN: The structured clone algorithm; WHATWG: HTML Standard, Structured data

Topic: Two names, one object, and copies · standards, mistakes

Objects without classes

Objects can exist without any class. Self is an object-oriented language based on the concept of prototypes, and it began as a dialect of Smalltalk. Its own site describes it as a prototype-based dynamic language built on simplicity, uniformity, concreteness and liveness. In such a language an object is made directly, the way a JavaScript factory function makes one, with no class first.

Why it fits here: It explains why this topic can make objects with a plain function: in a prototype-based language, objects need no class to come from.

Sources: Wikipedia: Self (programming language); The Self language

Topic: Methods and this · history, languages

Classes built on prototypes

The class keyword came late. ECMAScript 2015 added Class Definitions, and MDN explains that classes in JS are built on prototypes, with some syntax and meaning of their own. So a class is mostly a tidier way to write objects that share methods through a prototype, which JavaScript could already do. Factory functions remain a plain, working way to build many objects.

Why it fits here: It places this topic's factory functions in history: they did the work of classes long before the class keyword existed.

Sources: ECMAScript 2015 Language Specification; MDN: Classes

Topic: Methods and this · history, standards

Grouping without a loop

Grouping a list, such as students by class or orders by city, once took a hand-written loop. Object.groupBy now does it: it groups the elements of an iterable according to the string values a callback returns, and gives back an object with one property per group. MDN shows it working across browsers since March 2024, and the standard lists it as Object.groupBy ( items, callback ).

Why it fits here: It saves this topic's most common loop over an array of objects: sorting items into groups by one property.

Sources: MDN: Object.groupBy(); ECMAScript Language Specification: Object.groupBy

Topic: Looping over an object, and arrays of objects · standards, tools

Values and entries arrived later

Turning an object into arrays was not always complete. Object.keys was already in ECMAScript 5.1; Object.values and Object.entries followed in ECMAScript 2017, a proposal championed by Jordan Harband according to TC39's list of finished proposals. Before them, getting each value meant looping over the keys and reading every property by hand.

Why it fits here: It explains why older code reaches values through keys, where this topic uses Object.values and Object.entries directly.

Sources: TC39: Finished Proposals; MDN: Object.entries(); ECMAScript 5.1 Language Specification

Topic: Looping over an object, and arrays of objects · history, standards

A format from a subset

JSON was not invented from nothing. Its home page says it is based on a subset of the JavaScript Programming Language Standard, ECMA-262 3rd Edition of December 1999. Its standard today, RFC 8259, calls it a lightweight, text-based, language-independent data interchange format, derived from the ECMAScript standard. So JSON looks like JavaScript, and nearly every language reads it.

Why it fits here: It explains why this topic's JSON looks so much like an object literal: it was taken from JavaScript's own way of writing objects.

Sources: JSON.org: Introducing JSON; RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Topic: Objects inside objects, and JSON · history, standards

What JSON leaves out

Not every value survives the trip into JSON. MDN explains that undefined, functions and symbols are not valid JSON values: JSON.stringify leaves them out of an object, or writes null in their place in an array. Infinity and NaN become null too, because the JSON standard does not permit them. So a value can come back from JSON.parse with less than it had.

Why it fits here: It is a trap of this topic's JSON: stringify a student with an undefined field, and that field is gone after parse.

Sources: MDN: JSON.stringify(); RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Topic: Objects inside objects, and JSON · standards, mistakes

Lesson 8: The DOM

Spaces are nodes too

The spaces and line breaks between tags are not thrown away. MDN explains that whitespace between HTML tags becomes text nodes in the DOM, and javascript.info adds that spaces and newlines are valid characters, like letters and digits. So a list written on five lines holds text nodes of spaces between its items. A script that walks every node of the tree meets them too.

Why it fits here: It explains a surprise in this topic's tree: between the element nodes sit text nodes made only of spaces and line breaks.

Sources: MDN: How whitespace is handled by HTML, CSS, and in the DOM; javascript.info: DOM tree

Topic: The page as a tree · standards, mistakes

How big is too big

A tree can grow too big. Lighthouse, Chrome's tool for grading pages, warns when the body element holds more than about 800 nodes, and reports an error above about 1400. Its guide explains the cost: as people and scripts use a page, the browser must keep working out the position and style of its nodes, and a large tree with complicated style rules can badly slow the page down.

Why it fits here: It puts a number on this topic's tree: every element is a node the browser must place and style, so a page should not hold thousands it does not need.

Source: Chrome for Developers: Avoid an excessive DOM size

Topic: The page as a tree · tools, numbers

Live lists and frozen lists

Some lists of elements keep themselves up to date. The DOM standard says a collection can be live or static, and is live unless stated otherwise: it follows the page as the page changes. MDN notes that querySelectorAll is the only method that returns a static NodeList, a snapshot taken at the moment of the call. So an element added later joins a live list, but never the snapshot.

Why it fits here: It explains why a list from this topic's querySelectorAll does not grow when the page later gains a matching element.

Sources: WHATWG: DOM Standard; MDN: NodeList

Topic: Finding elements · standards, mistakes

Two elements, one id

An id is meant to belong to one element: the HTML standard says it must be unique among all the ids in its tree. Pages still break the rule, and the DOM standard says what happens then. The method getElementById returns the first matching element in tree order, which is a preorder, depth-first walk: the order the tags appear in the page. The second element is never found by its id.

Why it fits here: It answers this topic's question about ids: a repeated id is a bug in the page, and the search quietly gives only the first.

Sources: WHATWG: HTML Standard, the id attribute; WHATWG: DOM Standard

Topic: Finding elements · standards, mistakes

Script tags that never run

A script tag put in through innerHTML does nothing: the HTML standard says scripts inserted that way do not execute at all. That does not make innerHTML safe. MDN calls it probably the most common route for cross-site scripting attacks, because HTML has many other ways to run code. Its own example is an image with a broken address, whose error handler runs the attacker's code.

Why it fits here: It is the reason behind this topic's rule: typed text goes into textContent, because innerHTML can run code without any script tag.

Sources: WHATWG: HTML Standard, the script element; MDN: Element.innerHTML

Topic: Changing what an element shows · standards, privacy

Why float was once cssFloat

Most CSS names change only to camelCase in JavaScript, but float got a new name. In 1999 the third edition of the JavaScript standard listed float among its future reserved words, and the W3C's style interface of November 2000 named the property cssFloat. MDN compares it with the class attribute, read as className. Modern browsers accept style.float as well, and today's standard still keeps cssFloat.

Why it fits here: It adds the one odd case to this topic's camelCase rule: the float property was once reached only as cssFloat.

Sources: ECMAScript Language Specification, 3rd edition (December 1999); W3C: Document Object Model (DOM) Level 2 Style Specification; MDN: float; CSS Object Model (CSSOM)

Topic: Changing what an element shows · history, words

One element, one place

An element can stand in only one place in the tree. MDN notes that appending an element that is already in the document moves it from its current position to the new one. The DOM standard's steps show why: if the node already has a parent, it is removed from that parent first. So append never makes a copy; to show the same thing twice, a script must make a second element.

Why it fits here: It answers this topic's question about appending an element already on the page: it moves, and its old place is left empty.

Sources: MDN: Node.appendChild(); WHATWG: DOM Standard

Topic: Making and removing elements · standards, mistakes

A move that keeps its state

Moving an element the usual way removes it and puts it back, and that can reset it. MDN lists what would be reset: animations, an iframe's loading state, focus and more. Chrome 133 added a method, moveBefore(), that moves an element without losing that state. MDN marks it as limited availability for now: it does not yet work in some of the most widely used browsers.

Why it fits here: It shows a limit of this topic's append: a moved element can lose its focus or animation, which a newer method avoids.

Sources: MDN: Element.moveBefore(); Chrome for Developers: Preserve state during DOM mutations with moveBefore()

Topic: Making and removing elements · browsers, tools

Modules wait without being asked

A script of type module waits by itself. The HTML standard says a module script is fetched while the page is read, and run when the page has finished parsing, the same as a defer script. It adds that the defer attribute has no effect on module scripts. So a module script at the top of the page can already find every element below it.

Why it fits here: It adds a third way to this topic's two: a module script waits for the whole page, like defer, without being told.

Source: WHATWG: HTML Standard, the script element

Topic: Where a script stands · standards, tricks

The moment the tree is ready

Pages have an event for the moment the tree is complete: DOMContentLoaded. The HTML standard fires it at the document when parsing ends. MDN notes that it comes after deferred scripts, but does not wait for images, subframes or async scripts. A script that cannot use defer can listen for this event instead, and start its work only when every element exists.

Why it fits here: It names the moment this topic's defer scripts wait for: the tree is complete, though pictures may still be loading.

Sources: WHATWG: HTML Standard, parsing HTML documents; MDN: Document: DOMContentLoaded event

Topic: Where a script stands · standards, browsers

A billion comparisons

Rebuilding a whole list is the plain way; libraries such as React try to change only what differs. React's own guide explains that the best general methods for comparing two trees take time on the order of n3, so 1000 elements would need about one billion comparisons. React uses a quicker rule of thumb instead, and asks for a key on each list item so it can match old items with new ones.

Why it fits here: It shows how big libraries avoid this topic's rebuild from scratch: they compare the new list with the old and change only the differences.

Sources: React (legacy docs): Reconciliation; React: Rendering Lists

Topic: Building a page from data · numbers, tools

Emptying in one call

An element can be emptied in one call. The DOM standard's replaceChildren() swaps all of an element's children for the nodes it is given, so called with nothing, it leaves the element empty. MDN calls it a very convenient way to empty a node, and shows it working across browsers since October 2020, so code older than that empties its lists in other ways.

Why it fits here: It is the tool this topic uses to update a list: one call clears the old items before the loop builds the new ones.

Sources: WHATWG: DOM Standard; MDN: Element.replaceChildren()

Topic: Building a page from data · standards, tools

Lesson 9: Events

A promise not to stop scrolling

A listener can promise not to stop scrolling. The option passive: true says the handler will never call preventDefault, and MDN explains that the browser then does not need to wait for it before scrolling. The DOM standard now makes passive the default for touchstart, touchmove, wheel and mousewheel listeners on the window and the document. So a page that listens for touches everywhere still scrolls at once.

Why it fits here: It adds a third argument to this topic's addEventListener: an options object, which can tell the browser that scrolling need not wait.

Sources: MDN: EventTarget.addEventListener(); WHATWG: DOM Standard

Topic: Listening for an event · browsers, tricks

A click waits its turn

A click never interrupts code that is already running. MDN calls JavaScript's rule run-to-completion: each job is processed completely before any other job is processed. A click during a long loop waits in a queue, and its handler runs only when the loop has ended. MDN names the cost too: while a job takes too long, the page cannot answer clicks or scrolling.

Why it fits here: It explains this topic's later: a handler never cuts into running code, but waits until the browser is free to call it.

Sources: MDN: JavaScript execution model; WHATWG: HTML Standard, event loops

Topic: Listening for an event · standards, mistakes

Which key, or which letter

A key has two names. The property event.key gives the character it typed, while event.code names the physical key, whatever its label. The code KeyQ is the Q key on a US keyboard, but the key labelled A on a French AZERTY one. So games read code, and the four keys for moving stay in one place on every layout; text boxes read key.

Why it fits here: It sharpens this topic's event.key: key reports the letter typed, and code reports where the finger pressed.

Sources: MDN: KeyboardEvent.code; W3C: UI Events KeyboardEvent code Values

Topic: The event object · standards, tricks

Real clicks and made-up clicks

A script can make up an event and send it with dispatchEvent, and handlers run as if a person had acted. The event object tells the difference: isTrusted is true when the browser made the event, and false when a script dispatched it. The DOM standard names one old exception: a click made by the click() method comes from the browser, yet is marked false.

Why it fits here: It adds one more fact this topic's event object carries: whether the browser, or a script, caused the event.

Sources: WHATWG: DOM Standard; MDN: Event.isTrusted

Topic: The event object · standards, tricks

Enter sends the form

A form can be sent without a click. The HTML standard calls it implicit submission: on some platforms, pressing Enter in a text box submits the form. If the form has a submit button, the browser fires a click at it. If it has none, a form with a single text box is sent all the same, with no click anywhere. Only the form's submit event is sure to hear every case.

Why it fits here: It explains this topic's advice to listen for submit on the form: Enter can send a form without any button being pressed.

Source: WHATWG: HTML Standard, implicit submission

Topic: Typing, choosing and sending forms · standards, tricks

A send that skips the listener

Calling form.submit() from a script sends a form quietly. MDN lists the differences: no submit event is raised, so submit listeners never run, and the browser's checks on the fields are not triggered. The newer requestSubmit() behaves like pressing the form's submit button, events and checks included, and has worked across browsers since September 2022.

Why it fits here: It warns about this topic's submit listener: a form sent by form.submit() never fires it, so its checks are skipped.

Sources: MDN: HTMLFormElement.submit(); MDN: HTMLFormElement.requestSubmit(); WHATWG: HTML Standard, form submission

Topic: Typing, choosing and sending forms · mistakes, browsers

Down first, then up

Bubbling settled a quarrel between browsers. Netscape sent an event from the outer element to the inner one, which is called capturing; Microsoft sent it from the inner element out, which is bubbling. The W3C took a middle position: an event is first captured down to its target, and then bubbles up again. The DOM standard keeps both, as a capturing phase and a bubbling phase.

Why it fits here: It shows the hidden half of this topic's bubbling: before an event rises, it first travels down from the top to its target.

Sources: QuirksMode: Event order; Wikipedia: DOM event; WHATWG: DOM Standard

Topic: How an event travels: bubbling · history, browsers

Gone when the handler ends

The property currentTarget lives only while a handler runs. MDN warns that outside an event handler it will be null, and the DOM standard's dispatch ends by setting the event's currentTarget to null. So an event kept in a variable and read after the handler has finished shows currentTarget as null, even though it pointed at an element a moment before.

Why it fits here: It warns about this topic's currentTarget: read it inside the handler, because once the handler ends, it is gone.

Sources: MDN: Event.currentTarget; WHATWG: DOM Standard

Topic: How an event travels: bubbling · standards, mistakes

Now and in the future

Delegation became famous through a library. jQuery 1.3 added a method called .live(), which attached a handler for all elements matching a selector, now and in the future. Its documentation explains how: it attached delegated handlers to the document itself. jQuery deprecated .live() in version 1.7 and removed it in 1.9, asking people to use .on() instead.

Why it fits here: It shows how old this topic's trick is: a popular library built a whole method on one listener at the top of the page.

Source: jQuery API Documentation: .live()

Topic: One listener for many: delegation · history, tools

Events that stay put

Delegation needs bubbling, and not every event bubbles. MDN notes that focus does not bubble, but the related focusin event that follows it does; blur and focusout are the same kind of pair. So one listener on a form cannot hear focus on each box, but it can hear focusin. javascript.info adds a historical twist: focus and blur still travel down in the capturing phase.

Why it fits here: It marks the limit of this topic's trick: an event that does not bubble never rises to the parent's listener.

Sources: MDN: Element: focus event; MDN: Element: blur event; javascript.info: Focusing: focus/blur

Topic: One listener for many: delegation · standards, mistakes

One signal removes them all

Taking listeners off once needed a name for every handler. The signal option changes that: MDN explains that a listener added with a signal is removed when the abort() method of its AbortController is called. The DOM standard does it with abort steps attached to each listener. One controller can serve many listeners, so a single abort() removes them all, arrow functions included.

Why it fits here: It solves this topic's arrow problem: a listener added with a signal can be removed without keeping its function in a name.

Sources: MDN: EventTarget.addEventListener(); WHATWG: DOM Standard

Topic: Removing listeners, once, and onclick · standards, tricks

A list of every listener

Chrome's console can show the listeners on any element. Its Console Utilities include getEventListeners(object), which returns the listeners registered on an object, grouped by event type, such as click or keydown. These utilities work only when typed into the DevTools Console, not in a page's own scripts. So checking that a listener was really removed takes one line.

Why it fits here: It gives a way to check this topic's removals: list an element's listeners before and after, and see the handler gone.

Source: Chrome for Developers: Console Utilities API reference

Topic: Removing listeners, once, and onclick · tools, browsers

Lesson 10: Errors and debugging

An error that holds many errors

One kind of error holds a whole list of others. MDN describes AggregateError as the error for when several errors need to be wrapped in a single error: Promise.any, for example, throws it when every task given to it fails. Its errors property is an array of the failures, one for each task. The standard's 2021 edition already defines it.

Why it fits here: It adds one more kind to this topic's list: an error whose job is to carry several other errors at once.

Sources: MDN: AggregateError; ECMAScript 2021 Language Specification

Topic: Errors are objects · standards, tools

One mistake, two names

The same runaway recursion has different names in different browsers. MDN lists them: Chrome and Safari throw a RangeError, Maximum call stack size exceeded, while Firefox throws an InternalError, too much recursion. InternalError is not in the standard at all, and Firefox's own list of messages files the error under it. So code that checks err.name for one browser can miss the other.

Why it fits here: It warns about this topic's kinds: a few errors come from the engine, not the standard, and their names differ between browsers.

Sources: MDN: InternalError: too much recursion; MDN: InternalError; Firefox source code: ErrorNumbers.msg

Topic: Errors are objects · browsers, mistakes

The trace is made at new

An error's trace is written when the error is made, not when it is thrown. V8, the engine in Chrome and Node.js, says the trace is collected when the error is created, and stays the same wherever, and however often, the error is thrown. ESLint's guide gives this as the reason to throw Error objects: they keep track of where they were built.

Why it fits here: It explains this topic's rule against throwing a plain string: only an Error object records where it was built.

Sources: V8: Stack trace API; ESLint: no-throw-literal

Topic: Throwing an error of your own · tools, mistakes

The standard's own RangeError

The standard throws RangeError too, for numbers outside what a function allows. The method toFixed, which rounds a number to a set count of decimal places, takes from 0 to 100 digits. MDN notes that any other count throws a RangeError, and the standard's own steps say the same. So (2.5).toFixed(101) stops with an error instead of guessing.

Why it fits here: It is a model for this topic's choice of kind: a number outside the allowed range is a RangeError, in the standard's own code.

Sources: MDN: Number.prototype.toFixed(); ECMAScript Language Specification: Number.prototype.toFixed

Topic: Throwing an error of your own · standards, numbers

A return in finally wins

A return inside finally beats every other return. MDN explains that a return in the try block is held back while finally runs, and a return in finally then overrides it, value and all. Even a planned throw gives way, and the function returns instead. ESLint's guide calls this unexpected behaviour, and its recommended rules forbid return, throw, break and continue in finally.

Why it fits here: It answers this topic's question about two returns: the one in finally wins, which is why finally should only clean up.

Sources: MDN: try...catch; ESLint: no-unsafe-finally

Topic: Catching: try, catch and finally · mistakes, tools

finally began as unwind-protect

The block that always runs is older than JavaScript. Wikipedia traces the clean-up now called finally to NIL, a Lisp of the mid to late 1970s, where it was UNWIND-PROTECT. Common Lisp kept the name: its standard says unwind-protect guarantees that the clean-up forms run, whether the protected form ends normally or is aborted. The name says it: protect the clean-up while unwinding.

Why it fits here: It gives this topic's finally a history: the promise to run clean-up code, whatever happens, was made in Lisp first.

Sources: Wikipedia: Exception handling (programming); Common Lisp HyperSpec: Special Operator UNWIND-PROTECT

Topic: Catching: try, catch and finally · history, languages

An error with a cause

A new error made in a catch can now keep the old one. Since ECMAScript 2022, an error can carry its cause: new Error("Settings are broken", { cause: err }). MDN explains that cause is used when catching and rethrowing an error with a more useful message, while keeping access to the original error. TC39's list of finished proposals names the people behind it, Chengzhong Wu and Hemanth HM.

Why it fits here: It improves this topic's rethrow: the new error can keep the old one as its cause, so nothing is lost on the way up.

Sources: MDN: Error: cause; ECMAScript 2022 Language Specification; TC39: Finished Proposals

Topic: Where to catch, and where to let it fly · standards, people

Why catch and throw were made

The words catch and throw were born from a swallowed error. In MacLisp, an early Lisp, programmers used the error trap ERRSET for jumps that had nothing to do with errors, and it quietly trapped unexpected errors too, making programs harder to debug. So in June 1972 MacLisp gained a new pair, CATCH and THROW, and ERRSET went back to trapping errors only.

Why it fits here: It is this topic's rule in its oldest form: a catch that traps every error hides the ones nobody expected.

Sources: Guy L. Steele Jr. and Richard P. Gabriel: The Evolution of Lisp; Wikipedia: Exception handling (programming)

Topic: Where to catch, and where to let it fly · history, languages

Assertions, 1949

The idea of stating what must be true at each step goes back to 1949. At a Cambridge conference in June that year, held for the launch of the EDSAC computer, Alan Turing gave a talk called Checking a Large Routine. Turing suggested that the programmer should make a number of definite assertions, each checked on its own, from which the correctness of the whole program follows.

Why it fits here: It gives this topic's console.assert a famous ancestor: checking a program by stating, step by step, what must be true.

Sources: Wikipedia: Assertion (software development); arXiv: 1904.03917; Xavier Leroy, Collège de France: course slides

Topic: Checking at the edges: loud and early · history, people

Failing slowly

In 2004 Jim Shore gave this topic's idea a name in IEEE Software: fail fast. A program that works around problems by itself ends up failing slowly, carrying on after an error and failing in strange ways later. A fail-fast system, as Wikipedia defines it, immediately reports at its interface any condition likely to indicate a failure. It sounds fragile, Shore wrote, but it makes software more robust.

Why it fits here: It names this topic's habit: stop at the first sign of bad data, close to its cause, instead of carrying on.

Sources: Jim Shore: Fail Fast, IEEE Software; Wikipedia: Fail-fast system

Topic: Checking at the edges: loud and early · people, tools

896 lines cut to one

Cutting a bug down can be done by a program. In 1999 Andreas Zeller of Saarland University described delta debugging, which narrows down what makes a program fail until a minimal set remains. In one case study, a web page that made the Mozilla browser fail had 896 lines of HTML. The method cut them down to the single line that caused the failure.

Why it fits here: It automates this topic's cut-it-down step: a program tries smaller and smaller inputs until only the cause is left.

Sources: Wikipedia: Delta debugging; Andreas Zeller and Ralf Hildebrandt: Simplifying and Isolating Failure-Inducing Input

Topic: The method, on a whole program · tools, people

Steps, expected, actual

Browser makers ask for this method in every bug report. Mozilla's bug writing guidelines ask for precise steps to reproduce, the expected results and the actual results. If a bug shows up only now and then, they say, the reporter must give more information for the report to be useful. A fix can only be checked against a bug that can be made to happen again.

Why it fits here: It shows this topic's first step in real use: a bug report begins with the input and steps that make the bug happen.

Source: Mozilla: Bug Writing Guidelines

Topic: The method, on a whole program · tools, browsers