Chapter 5: Vanilla JavaScript
Introduces Vanilla JavaScript’s role in web apps and explains why ECMAScript versioning matters when code is shipped without a framework build process.
After this chapter you will be able to
- Vanilla JavaScript in Web Apps. Explain what Vanilla JavaScript means in this book and how it adds dynamic behavior to HTML and CSS.
- ECMAScript Versions and Shipping Code. Explain what ECMAScript versioning names and contrast the usual shipping of Vanilla JavaScript with code transpiled for a framework or library project.
- TC39 proposal stages. Describe how TC39 proposals for JavaScript syntax and core APIs move from Stage 0 to Stage 4, and what Stage 4 establishes.
- Browser support versus editions. Explain why feature adoption should be based on browser compatibility rather than an ECMAScript edition number, even for standardized features.
- New feature compatibility limits. Distinguish the compatibility risk of new syntax from that of new methods or constructors, and explain why code must work in the target engine.
- ESNext status and availability. Explain that ESNext is an unofficial name for prospective ECMAScript features at Stage 3 or Stage 4, and that newer browsers may already implement some of them before they enter the specification.
- Transpilation for older engines. Explain how a transpiler converts recent or unapproved JavaScript syntax into a more stable version before shipping, using optional chaining as the example.
- Polyfills and syntax transpilation. Distinguish a polyfill from a transpiler: a polyfill checks for a missing API at runtime and supplies an implementation, while a transpiler rewrites syntax before shipping. Explain why a polyfill cannot support new language syntax such as an operator.
- Module scope and sharing. Explain what is private to a module and how modules deliberately share functionality.
- Module graph resolution. Trace how the browser discovers a module’s dependencies and resolves the resulting graph.
- Live bindings and shared instances. Explain the observable effects of live bindings and evaluating each module only once.
- Live export bindings. Explain that an exported variable is a live binding: if its module updates the variable, importers see the new value rather than an earlier copy.
- Default and named exports. Distinguish a default export from named exports by their roles and limits: a module can have one default value and any number of named exports alongside it. Describe the stated import syntax for the default value.
- Module imports and browser paths. Explain that a module uses the import keyword at the top level to receive declarations or values exported by other modules, and state which path forms browser imports accept without an import map.
- Bare specifiers and import maps. Explain that a bare specifier is a string identifier such as "lodash" rather than an absolute or relative URL, and that an import map lets the browser resolve it by defining an object in a special <script> tag.
- Import waits and chained delays. Trace why an importing module waits for a dependency’s top-level await, and explain the cost when several modules create a chain of such waits.
- Module preloading and execution. Explain how module graphs are fetched and what modulepreload does and does not do.
- Module script execution order. Distinguish the normal execution order of module scripts from their behavior when async is added.
- On-demand module imports. Explain that dynamic import() loads a module when needed and returns a Promise resolving to its module namespace object. Describe the button-click example as using await import() to load the module.
- Dynamic import failure handling. Explain why import() needs failure handling and how a timeout can limit how long a lazy import waits before its promise is rejected.
- JSON import attributes. Explain how `with { type: 'json' }` works in static and dynamic imports and what a JSON module exports.
- Declared type security check. Justify why an import attribute’s declared type is more than a hint.
- Shared JSON module instance. Explain how import attributes affect module cache identity and what sharing means for imported JSON.
- Feature index module re-exports. Explain how re-exporting from index modules organizes a feature’s public API and allows internal refactoring without changing import paths across the app.
- Single evaluation per module URL. Explain that a module URL is evaluated only once and later imports return the same namespace object, so consumers share its state and side effects.
- Explicit module setup. Justify keeping top-level side effects minimal and exposing an explicit init() function called from app.js or another entry point instead of running setup on import.
- Module loading choices. Distinguish when to use static imports, dynamic import(), and preloading for application code.
- ES modules as architecture. Explain the architectural benefit the section attributes to these import patterns.
- Modern JavaScript foundations. Explain why ES2015 is a common starting point for modern JavaScript and how later additions benefit Vanilla projects, without needing to describe those additions yet.
- Safe nested property access. Explain that optional chaining (?.) lets code walk nested properties safely without throwing when a value is missing.
- Defaults for missing values. Distinguish ?? from || when choosing a default: ?? supplies one only for null or undefined, preserving values such as 0 or false.
- Logical assignment conditions. Distinguish when ||=, &&=, and ??= assign their right-hand side, and explain how to choose between ||= and ??= for defaults.
- Extracting and forwarding properties. Explain how destructuring and object rest/spread work together to take the properties you need and forward the remaining ones.
- Language-enforced private state. Distinguish a #private class field from an underscore-named property, explaining which can be accessed from outside the class.
- Object conversion helpers. Describe how Object.fromEntries, Object.entries, and Object.values provide quick object-to-iterable and iterable-to-object transformations.
- Built-in collection choices. Explain why Vanilla Web apps use more than plain arrays and objects for everyday data tasks, using the section’s examples of API responses, unique IDs, and DOM-element keys.
- Modern array method purposes. Explain the common tasks handled by includes, find/findIndex, flat/flatMap, and at, and how these methods reduce boilerplate.
- Non-mutating array copies. Explain what the ES2023 copy methods offer and why the section recommends them when you can choose.
- Set uniqueness and operations. Explain that a Set stores unique values, making it useful for avoiding duplicates without manual checks, and name the modern Set operations introduced here.
- Map keys and iteration. Explain how a Map differs from an object as a key–value store, and describe how its entries can be iterated.
- Weak collection object lifetimes. Explain why WeakMap and WeakSet use objects and how weak references make a WeakMap useful for metadata on DOM nodes. Contrast what happens to a node and its metadata in a WeakMap versus a regular Map.
- Functional programming in Vanilla JavaScript. Explain that functional programming in Vanilla JavaScript means writing functions that take input, return output, and avoid unexpected side effects, even though JavaScript is not a purely functional language.
- Declarative array transformations. Explain how array methods that accept functions let JavaScript code express the intended transformation instead of spelling out a manual loop.
- Pure functions and immutability. Explain that a pure function depends only on its inputs, produces the same output for the same inputs, and does not modify external state. Describe why combining purity with immutability helps make code easier to reason about.
- Readable function pipelines. Explain how chaining functions in plain JavaScript creates a pipeline of small, testable steps that reads almost like natural language, without requiring a library helper.
- Practical functional style benefits. Explain how pure functions, immutability, and array methods can improve Vanilla Web code without advanced functional programming patterns or additional libraries.
- Need for error management. Explain why a Vanilla JavaScript app must manage errors consistently, including errors that occur at runtime or asynchronously.
- Synchronous error handling and cleanup. Explain that synchronous code in a try block jumps to catch if it throws, and that an optional finally block can clean up resources whether the operation succeeds or fails.
- Error instances and subclasses. Explain that JavaScript errors are instances of Error or a subclass, and that creating and throwing your own error instances can provide debugging context.
- Asynchronous error handling. Explain why promise rejections should be caught explicitly and how to handle errors from await locally inside an async function.
- Global error safety nets. Distinguish what window.onerror and window.onunhandledrejection catch, and explain why global handlers are for logging and monitoring rather than controlling program flow or replacing structured error management.
- Local and asynchronous error handling. Explain that risky operations should be handled with local try/catch and promise rejections should be handled explicitly, including with catch handlers for async operations.
What it builds on
- Semantic HTML (chapter 3) · Semantic HTML as part of the interface JavaScript enhances.
- (chapter intro) (chapter 4) · CSS as another part of the interface JavaScript enhances.
Section by section
Introduction
Introduces Vanilla JavaScript’s role in web apps and explains why ECMAScript versioning matters when code is shipped without a framework build process.
- Vanilla JavaScript in Web Apps: Explain what Vanilla JavaScript means in this book and how it adds dynamic behavior to HTML and CSS.
Why it matters: This establishes what the book means by using JavaScript in a Vanilla Web project. - ECMAScript Versions and Shipping Code: Explain what ECMAScript versioning names and contrast the usual shipping of Vanilla JavaScript with code transpiled for a framework or library project.
Why it matters: It explains why language versions are especially relevant when the code you write is largely the code you ship.
Key terms: Vanilla JavaScript, core language, browser APIs, ECMAScript, versioning, transpiled
5.1 Versioning
This section explains how JavaScript features become standardized and why developers must check browser support rather than rely on proposal stages or ECMAScript edition names.
- TC39 proposal stages: Describe how TC39 proposals for JavaScript syntax and core APIs move from Stage 0 to Stage 4, and what Stage 4 establishes.
Why it matters: A proposal’s stage tells you about its standardization, not whether it is ready for all your users. - Browser support versus editions: Explain why feature adoption should be based on browser compatibility rather than an ECMAScript edition number, even for standardized features.
Why it matters: Checking the browsers your users run is more useful than assuming an edition label predicts feature availability. - Core language specification boundaries: Distinguish TC39’s responsibility for JavaScript’s core language from the specification of most browser and platform APIs.
Why it matters: Not every JavaScript-accessible browser feature follows the TC39 core-language proposal process. - ES2015 language milestone: Describe why ES2015 is singled out for readers familiar with early-2000s JavaScript, with examples of features introduced then and later.
Why it matters: These examples make the scale of JavaScript’s evolution since the early 2000s concrete.
Key terms: TC39, Stage 0, Stage 4, ECMAScript, ECMAScript edition, browser support, MDN, Baseline, CanIUse, core language specification
5.2 Latest additions to the language
This section highlights which recent ECMAScript additions are useful in Vanilla Web projects and warns that compatibility depends on the target JavaScript engine.
- New feature compatibility limits: Distinguish the compatibility risk of new syntax from that of new methods or constructors, and explain why code must work in the target engine.
Why it matters: This distinction helps you choose features that will work in the engines your project targets. - Everyday feature relevance: Explain why the usefulness of a recent ECMAScript addition depends on the Vanilla Web project, using the section’s examples.
Why it matters: It helps you focus on language features relevant to the app you are building.
Key terms: syntax, target engine, syntax errors, polyfilled, ES version, BigInt, async/await, modules, optional chaining
5.2.1 ESNext
Defines ESNext and explains why some of its features may already appear in newer browsers.
- ESNext status and availability: Explain that ESNext is an unofficial name for prospective ECMAScript features at Stage 3 or Stage 4, and that newer browsers may already implement some of them before they enter the specification.
Why it matters: The term ESNext does not mean a feature is already standardized or available in every browser.
Key terms: ECMAScript Next, ESNext, Stage 3, Stage 4
5.3 Using a transpiler
This section explains how transpilers make newer JavaScript syntax usable in older engines and what trade-offs that conversion brings.
- Transpilation for older engines: Explain how a transpiler converts recent or unapproved JavaScript syntax into a more stable version before shipping, using optional chaining as the example.
Why it matters: It lets you choose modern syntax while still shipping code that older browsers can parse. - Compatibility benefits and costs: Describe when transpilation may be useful or unnecessary and the trade-off it introduces.
Why it matters: It helps you decide whether the compatibility benefit is worth the cost for your target devices.
Key terms: transpiler, optional chaining, Babel, ES2019, compatibility, developer experience
5.4 Using polyfills
The section explains how polyfills provide missing APIs in older browsers, how they differ from transpilers, and why targeted polyfills suit Vanilla Web projects.
- Polyfills and syntax transpilation: Distinguish a polyfill from a transpiler: a polyfill checks for a missing API at runtime and supplies an implementation, while a transpiler rewrites syntax before shipping. Explain why a polyfill cannot support new language syntax such as an operator.
Why it matters: This distinction helps you choose the right compatibility strategy for the feature you want to use. - Targeted polyfills for compatibility: Explain why a Vanilla Web project might include small polyfills for only the APIs it needs rather than convert the entire codebase. Give the section’s array includes example as an API that could be added only when absent.
Why it matters: Adding only missing features can keep a Vanilla Web project’s compatibility approach lightweight.
Key terms: polyfill, transpiler, runtime, modern API, targeted polyfills, Vanilla Web, includes method
5.5 ECMAScript Modules
This section explains how browser-native ECMAScript modules are loaded, linked, evaluated, and scoped.
- Module script loading: Describe how an HTML document loads an external module script and when that script executes.
Why it matters: It connects the HTML entry point to the module code the browser runs. - Module scope and sharing: Explain what is private to a module and how modules deliberately share functionality.
Why it matters: Module scope prevents accidental globals while letting files share selected functionality. - Module graph resolution: Trace how the browser discovers a module’s dependencies and resolves the resulting graph.
Why it matters: The phases explain how imports are connected before module code runs. - Live bindings and shared instances: Explain the observable effects of live bindings and evaluating each module only once.
Why it matters: These effects determine whether importers observe updates and share state. - Cross origin module loading: State the condition for loading a module from another origin.
Why it matters: It explains why a valid module URL may still fail to load.
Key terms: <script>, src, type="module", module scope, export, import, globalThis, entry module, module graph, construction
5.5.1 Named exports
This subsection explains that ES module exports are live bindings and distinguishes a module’s default export from its named exports.
- Live export bindings: Explain that an exported variable is a live binding: if its module updates the variable, importers see the new value rather than an earlier copy.
Why it matters: It explains why imported values can reflect changes made by their exporting module. - Default and named exports: Distinguish a default export from named exports by their roles and limits: a module can have one default value and any number of named exports alongside it. Describe the stated import syntax for the default value.
Why it matters: The distinction helps readers recognize a module’s primary offering and its additional utilities.
Key terms: ESM exports, live bindings, default export, named export, curly braces
5.5.2 Importing modules
This subsection explains how modules import exports, what paths browser imports accept, and how a module can combine imports and re-export them.
- Module imports and browser paths: Explain that a module uses the import keyword at the top level to receive declarations or values exported by other modules, and state which path forms browser imports accept without an import map.
Why it matters: These rules help you connect modules using paths the browser can resolve. - Combined imports and re-exports: Describe how a module can use different import declarations together and can gather imports from many modules to re-export them together.
Why it matters: This lets one module serve as a shared entry point for exports from several others.
Key terms: import keyword, import declarations, relative and absolute URLs, import map, re-exporting, bundlers
5.5.3 Import Maps
This section explains how import maps let browsers resolve bare module specifiers and when a bundler may still be useful.
- Bare specifiers and import maps: Explain that a bare specifier is a string identifier such as "lodash" rather than an absolute or relative URL, and that an import map lets the browser resolve it by defining an object in a special <script> tag.
Why it matters: It explains how an import can name a module without spelling out its URL. - Import maps versus bundlers: Distinguish browser resolution through import maps from bundler mapping of bare specifiers, and describe the kinds of projects for which the section favors each approach.
Why it matters: It helps you choose browser resolution without assuming import maps replace every build step.
Key terms: bare specifier, Import Maps, bundler, code splitting, minification, tree-shaking
5.5.4 Top-level await
This section explains how top-level await initializes a module, delays importing modules, and can create costly chains of waits.
- Top-level module initialization: Explain that a module can use await outside a wrapper function for configuration or one-time initialization.
Why it matters: It provides a direct way to finish setup before other modules use the result. - Import waits and chained delays: Trace why an importing module waits for a dependency’s top-level await, and explain the cost when several modules create a chain of such waits.
Why it matters: A convenient initialization step can delay every module that depends on it.
Key terms: top-level await, configuration, one-time initialization, module, dependency, lazy-load, first paint
5.5.5 Preloading and execution order
Explains how modulepreload affects module fetching without executing code, and how async changes the execution order of module scripts.
- Module preloading and execution: Explain how module graphs are fetched and what modulepreload does and does not do.
Why it matters: It helps you start loading modules earlier without mistaking a preload for a way to run code. - Module script execution order: Distinguish the normal execution order of module scripts from their behavior when async is added.
Why it matters: It helps you avoid relying on document order when an async module may run first.
Key terms: module graph, modulepreload, static import, dynamic import, module scripts, defer, async, dependency graph
5.5.6 Lazy loading
This subsection explains on-demand module loading with dynamic import() and notes that preloading can reduce its latency.
- On-demand module imports: Explain that dynamic import() loads a module when needed and returns a Promise resolving to its module namespace object. Describe the button-click example as using await import() to load the module.
Why it matters: It lets an app load code for routes, rare actions, or heavy widgets only when needed. - Preloading on-demand modules: Explain why preloading a module that may later be loaded on demand is useful.
Why it matters: It can make an on-demand module available sooner when the user needs it.
Key terms: dynamic import(), Promise, module namespace object, await import(), preloading, on demand, latency
5.5.7 Error handling and timeouts for dynamic imports
Dynamic imports use the network, so callers should handle failures and consider timeouts.
- Dynamic import failure handling: Explain why import() needs failure handling and how a timeout can limit how long a lazy import waits before its promise is rejected.
Why it matters: A lazy-loaded module can fail or take too long to arrive, so the app should account for both outcomes.
Key terms: dynamic imports, import(), lazyImport, timeout, promise
5.5.8 Import attributes and JSON modules
Explains how import attributes load JSON and CSS modules, why declared types matter for security and caching, and what to do when targeting older engines.
- JSON import attributes: Explain how `with { type: 'json' }` works in static and dynamic imports and what a JSON module exports.
Why it matters: This lets you import JSON using the module system without mistaking it for a JavaScript module with named exports. - Declared type security check: Justify why an import attribute’s declared type is more than a hint.
Why it matters: Declaring JSON also guards against receiving executable code in place of data. - Shared JSON module instance: Explain how import attributes affect module cache identity and what sharing means for imported JSON.
Why it matters: Shared mutable JSON can produce changes in another importer that you did not expect. - CSS stylesheet import: Describe the section’s CSS use of import attributes and its application to web components.
Why it matters: Import attributes are not limited to JSON; they can also provide a stylesheet object for components. - Syntax and engine compatibility: Distinguish the preferred import-attribute syntax from the deprecated form and state the suggested older-engine fallbacks.
Why it matters: Older examples and engines may require you to recognize obsolete syntax or choose a fallback.
Key terms: import attributes, with { type: 'json' }, default export, module namespace, type, security check, declared type, module’s identity in the cache, single-evaluation, shared-instance
5.5.9 Re-exports and module organization
Re-exporting from index modules gives features a clear public API and stable import paths, with a tree-shaking consideration for bundler users.
- Feature index module re-exports: Explain how re-exporting from index modules organizes a feature’s public API and allows internal refactoring without changing import paths across the app.
Why it matters: A clear public API lets you reorganize a feature without updating imports throughout the app. - Tree shaking re-export choice: State the section’s recommendation for re-exports when using a bundler with tree shaking.
Why it matters: The choice of re-export style can matter when a bundler performs tree shaking.
Key terms: re-exporting, index modules, public API surfaces, import paths, tree shaking, explicit named re-exports, export *, barrels
5.5.10 Caching, single evaluation, and side effects
This subsection explains how repeated imports share a module’s evaluation and state, why setup should be explicit, and when a classic fallback may be needed.
- Single evaluation per module URL: Explain that a module URL is evaluated only once and later imports return the same namespace object, so consumers share its state and side effects.
Why it matters: This helps explain why importing a module in several places does not reset it. - Explicit module setup: Justify keeping top-level side effects minimal and exposing an explicit init() function called from app.js or another entry point instead of running setup on import.
Why it matters: An explicit setup call makes it easier to tell when a shared module changes the app. - Legacy classic fallback: State that a legacy browser such as Internet Explorer 11 may need a classic fallback paired with a modern module entry, although this is now uncommon because ES modules are widely available.
Why it matters: It distinguishes a rare compatibility requirement from the normal modern-module approach.
Key terms: module URL, namespace object, state, side effects, top-level side effects, init(), entry point, load order, classic fallback, modern module entry
5.5.11 Practical rules of thumb
Provides practical choices for loading ES modules and explains how those choices support a framework-free project architecture.
- Module loading choices: Distinguish when to use static imports, dynamic import(), and preloading for application code.
Why it matters: These choices help you load essential code immediately and defer code that is not yet needed. - Top-level await restraint: Explain the recommendation for avoiding long top-level await chains.
Why it matters: This keeps heavy work out of the initial module-loading path. - Bare specifier setup: State how to use bare specifiers without a build step.
Why it matters: It gives you a way to use bare specifiers while keeping module URLs and versions explicit. - ES modules as architecture: Explain the architectural benefit the section attributes to these import patterns.
Why it matters: The import choices form an approach to organizing and delivering a project, not just individual syntax choices.
Key terms: static imports, dynamic import(), preload, critical path, top-level await, first render, bare specifiers, import map, stable URLs, ES modules
5.6 Modern JavaScript Essentials
The section frames ES2015 and async/await as familiar foundations for the later JavaScript features used in Vanilla Web apps.
- Modern JavaScript foundations: Explain why ES2015 is a common starting point for modern JavaScript and how later additions benefit Vanilla projects, without needing to describe those additions yet.
Why it matters: This gives you a baseline for understanding why the chapter discusses features added after ES2017.
Key terms: modern JavaScript, ES2015/ES6, async/await, boilerplate
5.6.1 Optional chaining and nullish coalescing
This section introduces optional chaining and nullish coalescing as ways to reduce defensive code when accessing properties and choosing defaults.
- Safe nested property access: Explain that optional chaining (?.) lets code walk nested properties safely without throwing when a value is missing.
Why it matters: It helps you explain why nested property access needs fewer defensive checks. - Defaults for missing values: Distinguish ?? from || when choosing a default: ?? supplies one only for null or undefined, preserving values such as 0 or false.
Why it matters: It helps you keep valid values instead of accidentally replacing them with defaults.
Key terms: optional chaining, ?., nullish coalescing, ??, ||, null, undefined
5.6.2 Logical assignment operators
This section explains when each logical assignment operator assigns a value and why choosing between falsy and nullish defaults matters.
- Logical assignment conditions: Distinguish when ||=, &&=, and ??= assign their right-hand side, and explain how to choose between ||= and ??= for defaults.
Why it matters: Choosing the wrong defaulting operator can replace valid data. - Short circuit assignment behavior: Explain when the right-hand side of a logical assignment expression is evaluated.
Why it matters: A skipped assignment also skips evaluating the expression that would supply its value.
Key terms: logical assignment operators, ||=, &&=, ??=, falsy, truthy, short-circuit, right-hand side, left-hand side
5.6.3 Destructuring + rest/spread in practice
Shows how destructuring with object rest/spread helps extract and forward properties, while warning that object spread makes only a shallow copy.
- Extracting and forwarding properties: Explain how destructuring and object rest/spread work together to take the properties you need and forward the remaining ones.
Why it matters: This pattern lets you use selected properties without discarding the others. - Shallow object spread copies: Explain why spreading an object may require additional copies of its nested objects or arrays.
Why it matters: Recognizing the shallow copy helps you avoid unintended changes to nested data.
Key terms: destructuring, object rest/spread, rest and spread operators, object spread, shallow, nested structures
5.6.4 Classes with public & private fields
This section introduces modern class fields and explains why #private members provide stronger encapsulation than underscore-named properties.
- Language-enforced private state: Distinguish a #private class field from an underscore-named property, explaining which can be accessed from outside the class.
Why it matters: It helps you tell genuine encapsulation from a naming convention. - Modern class member features: Describe the class members named in this section and the benefits given for modern class syntax.
Why it matters: It explains what modern class syntax offers beyond conventionally named properties.
Key terms: private #value, _value, parse time, public fields, private fields, private methods/accessors, static fields, constructor boilerplate
5.6.5 Cleaner errors: optional catch binding and error cause
5.6.6 Small quality-of-life wins
This section highlights small JavaScript features that make common object, number, and string operations cleaner.
- Object conversion helpers: Describe how Object.fromEntries, Object.entries, and Object.values provide quick object-to-iterable and iterable-to-object transformations.
Why it matters: These helpers can make object transformations more concise. - Safer own-property check: State that Object.hasOwn(obj, key) is presented as a safer alternative to obj.hasOwnProperty(key).
Why it matters: It gives you a safer way to perform an own-property check. - Readable numeric separators: Explain that numeric separators improve the readability of large numbers, as in 1_000_000.
Why it matters: Separators make large numbers easier to scan in code. - Simpler string matching and replacement: Distinguish replaceAll as a way to avoid a global regex for simple replacements from matchAll as a way to iterate through all regex matches without manual loops or index tracking.
Why it matters: These methods reduce boilerplate in common string operations.
Key terms: Object.fromEntries, Object.entries, Object.values, Object.hasOwn, obj.hasOwnProperty, Numeric separators, String.prototype.replaceAll, String.prototype.matchAll
5.7 Collection Management
Introduces JavaScript collections as built-in tools for common Vanilla Web app data tasks.
- Built-in collection choices: Explain why Vanilla Web apps use more than plain arrays and objects for everyday data tasks, using the section’s examples of API responses, unique IDs, and DOM-element keys.
Why it matters: Choosing from built-in collections can simplify routine app work without adding a library.
Key terms: collections, arrays, sets, maps
5.7.1 Arrays
Defines arrays, identifies newer methods that simplify common operations, and recommends non-mutating copy methods when appropriate.
- Array structure: Describe an Array as an ordered, zero-indexed list that stores multiple values in one variable.
Why it matters: This gives you the basic model for understanding the methods that operate on arrays. - Modern array method purposes: Explain the common tasks handled by includes, find/findIndex, flat/flatMap, and at, and how these methods reduce boilerplate.
Why it matters: You can recognize a concise built-in method for several everyday array tasks. - Non-mutating array copies: Explain what the ES2023 copy methods offer and why the section recommends them when you can choose.
Why it matters: Choosing a non-mutating method can prevent an array operation from unexpectedly affecting other code.
Key terms: Array, ordered, zero-indexed, includes, find, findIndex, flat, flatMap, at, copy methods
5.7.2 Sets
This section introduces Sets as a way to store unique values and names modern operations available on them.
- Set uniqueness and operations: Explain that a Set stores unique values, making it useful for avoiding duplicates without manual checks, and name the modern Set operations introduced here.
Why it matters: A Set can remove the need to write your own duplicate checks.
Key terms: Set, unique values, union, intersection, difference, symmetricDifference
5.7.3 Maps
Introduces Maps as key–value stores with flexible key types, insertion order, and iteration APIs.
- Map keys and iteration: Explain how a Map differs from an object as a key–value store, and describe how its entries can be iterated.
Why it matters: These properties help you recognize when a Map suits DOM elements, configurations, or caching.
Key terms: Map, key–value store, insertion order, keys(), values(), entries()
5.7.4 Weak collections: memory-friendly
Explains how weak collections let metadata be associated with objects without keeping those objects alive.
- Weak collection object lifetimes: Explain why WeakMap and WeakSet use objects and how weak references make a WeakMap useful for metadata on DOM nodes. Contrast what happens to a node and its metadata in a WeakMap versus a regular Map.
Why it matters: Weak collections let you associate data with DOM nodes without retaining nodes that the rest of the app no longer uses.
Key terms: WeakMap, WeakSet, garbage collection, weakly, strong reference, metadata
5.8 Functional Programming
Introduces functional programming as a practical set of ideas already common in Vanilla JavaScript.
- Functional programming in Vanilla JavaScript: Explain that functional programming in Vanilla JavaScript means writing functions that take input, return output, and avoid unexpected side effects, even though JavaScript is not a purely functional language.
Why it matters: You can recognize and use functional ideas in ordinary JavaScript without adopting a different language or framework.
Key terms: functional programming, FP, side effects, Vanilla
5.8.1 Array transformations
This section presents array methods that take functions as a declarative alternative to manual loops.
- Declarative array transformations: Explain how array methods that accept functions let JavaScript code express the intended transformation instead of spelling out a manual loop.
Why it matters: It helps you recognize the functional-programming style the section is introducing.
Key terms: FP, higher-order methods, declarative, array methods
5.8.2 Pure functions and immutability
Defines a pure function and explains why pairing purity with immutability makes code easier to reason about.
- Pure functions and immutability: Explain that a pure function depends only on its inputs, produces the same output for the same inputs, and does not modify external state. Describe why combining purity with immutability helps make code easier to reason about.
Why it matters: Predictable results and unchanged external state make a function’s behavior easier to follow.
Key terms: pure function, inputs, external state, immutability
5.8.3 Function composition
This subsection explains that plain JavaScript can chain small functions into readable, testable pipelines.
- Readable function pipelines: Explain how chaining functions in plain JavaScript creates a pipeline of small, testable steps that reads almost like natural language, without requiring a library helper.
Why it matters: Small, readable steps make a sequence of operations easier to follow and test.
Key terms: function composition, pipelines, plain JavaScript
5.8.4 Everyday benefits
This section explains the everyday benefits of using a few functional programming practices in Vanilla Web code.
- Practical functional style benefits: Explain how pure functions, immutability, and array methods can improve Vanilla Web code without advanced functional programming patterns or additional libraries.
Why it matters: These benefits are available through everyday JavaScript practices, not just advanced patterns or libraries.
Key terms: pure functions, immutability, array methods, optional chaining, spread, functional style
5.9 Error Management
This section explains why Vanilla JavaScript apps need consistent error management without a framework handling errors for them.
- Need for error management: Explain why a Vanilla JavaScript app must manage errors consistently, including errors that occur at runtime or asynchronously.
Why it matters: Handling errors consistently makes failures less likely to go unnoticed and helps keep the app reliable.
Key terms: runtime, asynchronously, Vanilla project, silent failures
5.9.1 Exceptions and try/catch
This section explains how try/catch handles synchronous errors, how finally supports cleanup, and when a catch binding can be omitted.
- Synchronous error handling and cleanup: Explain that synchronous code in a try block jumps to catch if it throws, and that an optional finally block can clean up resources whether the operation succeeds or fails.
Why it matters: This gives you a direct way to respond to a synchronous error without skipping necessary cleanup. - Optional catch binding: State that, since ES2019, the catch binding can be omitted when the error object is not needed.
Why it matters: You can write a catch block without an unused error variable.
Key terms: try/catch, synchronous code, finally, catch binding, error object, ES2019
5.9.2 Error objects
This section explains JavaScript error objects, how a cause preserves an original error, and when AggregateError represents multiple errors.
- Error instances and subclasses: Explain that JavaScript errors are instances of Error or a subclass, and that creating and throwing your own error instances can provide debugging context.
Why it matters: An informative error object makes a failure easier to investigate. - Preserving an original cause: Describe how an error’s cause property preserves the original reason when rethrowing an error, so it can be inspected later.
Why it matters: Preserving the cause lets someone investigating a rethrown error find the original problem. - Grouping multiple errors: Explain that AggregateError wraps several errors into one when an operation needs to report multiple errors.
Why it matters: It gives an operation a way to report several failures together.
Key terms: Error, TypeError, ReferenceError, RangeError, cause, err.cause, AggregateError
5.9.3 Asynchronous errors
This subsection explains how to handle promise rejections and errors from await rather than leaving them unhandled.
- Asynchronous error handling: Explain why promise rejections should be caught explicitly and how to handle errors from await locally inside an async function.
Why it matters: Handling asynchronous errors where they occur helps avoid noisy logs or silent failures.
Key terms: promise rejections, async/await, unhandledrejection event, try/catch
5.9.4 Global handlers
This section identifies the browser’s global error handlers and explains their limited role as last-resort logging and monitoring safety nets.
- Global error safety nets: Distinguish what window.onerror and window.onunhandledrejection catch, and explain why global handlers are for logging and monitoring rather than controlling program flow or replacing structured error management.
Why it matters: Knowing their limits helps you monitor missed errors without relying on global handlers to manage normal program behavior.
Key terms: window.onerror, window.onunhandledrejection, logging, telemetry, structured error management
5.9.5 Practical guidance for error management
Summarizes where to handle errors in Vanilla JavaScript and why explicit handling makes applications more predictable and easier to debug.
- Local and asynchronous error handling: Explain that risky operations should be handled with local try/catch and promise rejections should be handled explicitly, including with catch handlers for async operations.
Why it matters: Handling failures explicitly helps prevent unhandled errors and makes problems easier to debug. - Informative errors and rethrowing: Describe the recommended form of a thrown error and what to consider when rethrowing one.
Why it matters: Clear errors make failures easier to interpret when debugging. - Global error event limits: State the role assigned to global error events in this guidance.
Why it matters: Global reporting can reveal failures, but it does not replace handling them explicitly.
Key terms: try/catch, promise rejections, catch handlers, Error instances, cause option, rethrowing, global error events, diagnostics, reporting
5.10 Summary
Where this is used later
- The API (chapter 6) · Introduces browser APIs used to work with the document.
- Browser Web APIs (chapter 6) · Helps distinguish Browser Web APIs from core JavaScript language features.
- Bundling and transpiling (chapter 9) · Provides context for decisions about transpiling a distributed web component.
- Registration (chapter 7) · Modules and their import-time execution.
- Packaging (chapter 14) · ES module imports and exports
- Basic tips (chapter 14) · Introduces ECMAScript modules.
- Importing dynamic modules (chapter 14) · Covers module preloading and execution order.
- The document metadata (chapter 15) · Module preloading and execution-order behavior.
Concepts explained in this chapter
- ECMAScript moduleAn ECMAScript module is a separately scoped JavaScript module with explicit import and export bindings.
- ECMAScript language specificationECMAScript is the standardized language specification from which JavaScript implementations derive their core syntax and semantics.
- JavaScriptA programming language standardized as ECMAScript and widely used to implement behavior in web browsers.
- promiseA JavaScript promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
- CORSCross-origin resource sharing is a web mechanism through which servers use HTTP headers to specify which other origins may access their resources.
- vanilla webAn approach to building websites and web applications with core web technologies and browser APIs without a framework defining the application architecture.
- Web APIsA programming interface exposed by a web browser for accessing web-platform or device capabilities.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
