Leanpub Header

Skip to main content

Topics

JavaScript

The programming language of the web, from its 1995 origins to today's frameworks, runtimes and tools, as told through the free samples of the Leanpub books about it.

Created from the free samples of 31 Leanpub books and the descriptions and tables of contents of 46 more, with every source cited.

JavaScript is a high-level, dynamically typed programming language that first shipped in Netscape Navigator in 1995 and has been standardised as ECMAScript by Ecma International since 1997. It began as a scripting language for web pages and is now one of the most widely used languages in software: every mainstream browser runs it, Node.js (2009) brought it to servers and command-line tools, and it is the language in which the web's user-interface frameworks, build tools and a large share of its libraries are written.

Its distinguishing features are first-class functions with closures, objects that delegate to one another through prototypes rather than being stamped from classes, a single-threaded, event-driven model of concurrency, and dynamic typing with implicit coercion between types. Since the 2015 edition of the standard (ES2015, also called ES6) the language has gained a new feature set each year, and TypeScript, a typed superset from Microsoft, is widely used alongside it.

This article describes the language, the runtimes it runs in, the frameworks and tools built on it, and the ways it is written, tested and attacked. Its sources are the free samples of the Leanpub books listed at the end: where a sample states something, the sentence cites it; the rest is general knowledge of the language.

Where to start

The sources sort themselves by how much JavaScript they assume. A reader with none of the web languages can begin with Fundamentals of HTML, SVG, CSS and JavaScript for Data Visualisation, which teaches only the subset of HTML, SVG, CSS and JavaScript that a chart needs and assumes none of them.[19] Two short books take the next step without a framework: JavaScript Functions, Closures, and Prototypes stays on functions, closures and prototypes,[3] and The Node Beginner Book builds a small web application from Node's HTTP module up.[39] The You Don't Know JS Yet series is not an introduction: its first volume assumes six to nine months of experience and asks the reader to learn all of the language rather than a safe subset.[1]

A reader who already writes JavaScript and wants a framework has an entry point for each: The Road to React grows one React application from the first component to deployment,[24] Understanding React reviews the JavaScript that React needs before the components,[25] and The Majesty of Vue.js 2 asks only for HTML and JavaScript, though it covers Vue 2 (2017).[26] Essential TypeScript adds types to JavaScript the reader already knows, from the 2016 state of the language.[17]

For a working developer the deeper reading is Functional-Light JavaScript on functional style,[11] JavaScript Allongé, the "Six" Edition on the language from functions outward,[15] and Frontend System Design Essentials on the problems of a large front end;[7] 50 TypeScript F*ck Ups is for the TypeScript user who already makes the mistakes it catalogues.[18]

History

JavaScript was written by Brendan Eich at Netscape in 1995, under the working names Mocha and LiveScript, and released as JavaScript in Netscape Navigator 2.0; the name was a marketing nod to Sun's Java, with which it shares little beyond C-style syntax. Microsoft shipped a compatible JScript in Internet Explorer 3 in 1996, and Netscape submitted the language to Ecma International for standardisation. The first edition of ECMA-262, the ECMAScript standard, appeared in June 1997; the third edition (1999) added regular expressions and exception handling and is the version the web ran on for a decade. A fourth edition that would have added classes and static types was abandoned in 2008, and the fifth (2009) added strict mode, JSON support and getters and setters instead.

The sixth edition, ES2015, was the largest change in the language's history: classes, modules, promises, arrow functions, block-scoped let and const, iterators and generators, template literals, destructuring and Map and Set. Since then the TC39 committee has published an edition every June: async/await in ES2017, optional chaining and nullish coalescing in ES2020, class fields and top-level await in ES2022. New features move through a staged proposal process before they reach the standard.

The language's reputation lagged its capabilities. Douglas Crockford's JavaScript: The Good Parts (2008) argued for using a disciplined subset of it. The You Don't Know JS Yet series takes the opposite position, exploring "all the parts", and disputes the common claim that JavaScript is a deeply flawed language that was poorly designed and inconsistently implemented.[1] Outside the browser, Ryan Dahl's Node.js (2009) paired the V8 engine from Google Chrome with an event-driven I/O library, and the npm registry (2010) grew into the largest package ecosystem of any language. Dahl's later runtime Deno (2018) and Bun (2022) are alternatives to Node that run the same language.

The language

JavaScript has seven primitive types (undefined, null, boolean, number, bigint, string and symbol) and objects, which are collections of named properties. Values carry their types; variables do not. The language converts between types implicitly in many operations, which is why the strict equality operator ===, which does not coerce, is generally preferred to ==.

Objects and properties

An object is a bag of properties whose values can be anything, including functions. Properties can be defined with descriptors that make them read-only, non-enumerable or computed through getters and setters, and objects can be copied shallowly with the spread syntax or deeply, including circular references, with the structuredClone function that web environments provide.[2] Optional chaining (a?.b) reads a property through a possibly missing value without throwing, and arrays are a specialised kind of object.[2]

Functions, scope and closures

Functions are values: they can be stored, passed and returned, and a function can be created inside another. Scope is lexical, decided by where a function is written rather than where it is called. Closure follows from that. One of the sources defines it concretely: closure is when a function remembers and continues to access variables from outside its scope, even when the function is executed in a different scope, and notes that closure is part of the nature of a function, so objects do not get closures.[1] Closures are the mechanism behind callbacks, event handlers, module patterns and memoisation, and alongside functions and prototypes they are a standing subject of interview questions.[3] Functions are themselves objects, with call, apply and bind for choosing what this means during a call.[3]

this and prototypes

The this keyword is, in one source's words, one of the language's most powerful mechanisms and one of its most misunderstood; a common misconception is that a function's this refers to the function itself, where in fact it is a dynamic execution context set by how the function was called.[1] Objects are related not by class membership but by prototype links: where this is a characteristic of function execution, a prototype is a characteristic of an object, specifically the resolution of a property access, and can be thought of as a linkage between two objects.[1] Object.create makes an object that delegates to another, and a property on the new object shadows the same-named one on its prototype.[1]

One Node.js text contrasts this with class-based languages as "blueprints versus finger-pointing": Java creates objects from a class blueprint, JavaScript creates them from scratch, as factory functions or constructor functions called with new, and shares behaviour by pointing at a prototype; its sample measures, with heap snapshots, the memory cost of giving each object its own copy of a method instead of putting the method on the prototype.[4] The class syntax added in ES2015 is written over this same mechanism rather than replacing it.

Iteration and collections

ES2015 defined an iterator protocol that for..of loops, the spread syntax and destructuring all consume. Arrays, strings, maps and sets are built-in iterables, and generator functions produce iterators lazily.[1] Arrays carry map, filter and reduce, and utility libraries fill the gaps: lodash, which shares the _ namespace with its predecessor Underscore and is a drop-in replacement for it, provides collection, array, object, function and string helpers, many of which have since gained native equivalents.[5]

Asynchrony and the event loop

A JavaScript program runs on one thread. Instead of blocking on input and output, it hands work to the host (a browser or Node.js) and continues; when the work completes, the host queues a callback that the event loop runs once the current task finishes. Early code expressed this with nested callbacks; ES2015 promises and ES2017 async/await let the same logic be written in sequence. Node.js introductions treat the event loop as the first thing to understand about the runtime, along with npm and its release versioning.[6]

The model has consequences for user interfaces. A search box that fires a request on every keystroke can receive responses out of order, so a later request's results are overwritten by stale data; the remedy is to cancel the previous request with an AbortController when a new one starts.[7] On the server, one thread means one core, and Node's cluster module forks worker processes so that one program can use several cores, with process managers such as PM2 handling restarts and graceful shutdown.[8]

Regular expressions and text

Regular expressions have been part of the language since ECMAScript 3, through RegExp objects and the string methods that accept them. They are a small language of their own for text processing, learned feature by feature: literal matching, the i and g flags, the RegExp constructor for patterns built at runtime, anchors for the start and end of strings, lines and words, alternation and grouping with their precedence rules, and the escaping of metacharacters.[9]

Modules and packages

Node.js adopted the CommonJS module format (require and module.exports) in 2009, browsers used AMD and script loaders, and ES2015 gave the language its own import/export syntax, supported natively in browsers from 2017 and in Node.js from 2020. Code is shared through npm packages described by a package.json file and versioned by semantic versioning; maintaining a package means keeping its dependencies, linting, type declarations, tests, continuous integration, releases and documentation in order, and for open-source work also funding, contributors and marketing.[10]

Programming styles

JavaScript supports procedural, object-oriented and functional styles, and most real programs mix them. Two of the styles have a particularly rich literature in this library.

Functional programming

Because functions are values and closures are cheap, JavaScript lends itself to composing small functions into larger ones. One source calls this process composition and describes it as how a functional programmer models the flow of data through a program, "the most foundational concept in all of FP"; its sample builds compose and pipe from scratch, derives them with reduce, recursion and lazy wrapping, shows partial application of the composers themselves, and refactors a nested callback into point-free style.[11] The same book argues for a practical subset it calls Functional-Light Programming, applied in balance rather than all or nothing, with the heavier vocabulary left to an appendix.[11]

That vocabulary, monads, functors, applicatives, foldables and semigroups, is explained in another source entirely through JavaScript code: a monad is treated as a pattern rather than a specific thing, built from a two-function Identity monad with a chain operation, and checked against the three monad laws of left identity, right identity and associativity.[12] A third treats function composition and object composition as two sides of one subject, from pure functions and currying through functors, lenses and transducers to factory functions and functional mixins, and argues that composition is harder with classes.[13] Elm, a separate language that compiles to JavaScript, takes the functional position to its end: compiler-enforced immutability, a single update function as the only place state changes, and a type system that works to prevent runtime errors; one source teaches it to React developers by comparison with the habits they already have.[14]

Objects, classes and patterns

The object-oriented style in JavaScript can be written with ES2015 classes, with constructor functions and prototypes directly, or with factory functions and mixins that compose behaviour without inheritance hierarchies.[13] A long-running treatment of the language works from functions outward, treating combinators, decorators and partial application as the core of the language before reaching iterators, generators, metaobjects, prototypes, classes and mixins.[15] Design, performance and rendering patterns are catalogued for plain JavaScript and React applications.[16]

Static typing with TypeScript

TypeScript, released by Microsoft in 2012, adds optional static types to JavaScript and compiles to it; any JavaScript program is a TypeScript program. Its type system infers types where it can, and adds interfaces, enums, generics, union types, declaration files for untyped libraries and source maps for debugging; an existing JavaScript codebase can be converted gradually.[17] As the language grew, so did its ways of going wrong: one source catalogues about fifty common mistakes, from strict mode and type assertions to utility types, discriminated unions, conditional types and decorators, organised around the slip-ups rather than a feature tour.[18] TypeScript is now the default language of the Angular framework and is common in React, Node.js and infrastructure code.

In the browser

The browser remains JavaScript's home. A page is a document the language can inspect and change through the Document Object Model (DOM); one source for data analysts puts it plainly: HTML and SVG describe elements, CSS describes their style and position, and JavaScript is a programming language that can manipulate HTML and SVG, do general computation such as data manipulation, and handle interaction.[19]

Data visualisation and D3

D3, Data-Driven Documents, is Mike Bostock's library (2011) for binding data to DOM and SVG elements. One source introduces it by contrasting the plain DOM code needed to add an element with D3's shorter declarative selections, and explains when to choose it over ready-made chart libraries such as Chart.js or HighCharts: when the chart has to be custom.[20] D3's scales, axes and layouts yield line and bar charts, histograms, tree, Sankey and bullet diagrams, maps from GeoJSON, tooltips and transitions.[21] When D3 is combined with a component framework the question is who controls the DOM; one early React text settles it with a single rule, React owns the DOM and D3 calculates the properties, and shows JSX compiling to React.createElement calls and a one-way, Flux-inspired data flow with one component holding state.[22]

Component frameworks

Modern web interfaces are built from components, and three frameworks dominate the library. React (Facebook, 2013) renders a tree of components to a virtual DOM and reconciles it with the real one. Its hooks API (version 16.8, 2019) replaced class components for most new code; the changes from version 16 onward, including the Context API for avoiding props drilling, React.memo, the Profiler, React.lazy with Suspense for code splitting, and hooks themselves, are documented in one source partly through comic strips.[23] Current introductions build one application from the first component through hooks, data fetching and, in React 19, forms driven by actions, with React Router for navigation and TypeScript for types.[24][25]

Vue (Evan You, 2014) attaches directives to HTML; its samples teach event handling with the v-on shorthand, event and key modifiers, computed properties and two-way binding with v-model through small apps such as a calculator.[26] Angular is two frameworks: AngularJS (Google, 2010) and the TypeScript rewrite released as Angular in 2016. Angular compiles templates either just in time, while the application bootstraps, or ahead of time, and for ahead-of-time compilation the component metadata has to be statically analysable, which rules out computing a template at runtime.[27] Its router models an application as router states, each an arrangement of components that defines what is visible on the screen, with the URL as a serialised router state and a navigation pipeline of redirects, recognition, guards, data resolution and activation.[28] Teams migrating from AngularJS can run both frameworks in one hybrid application, bridging the two dependency-injection systems with NgUpgrade and moving one vertical or horizontal slice at a time.[29] Aurelia (2015) pairs each view with a view-model by naming convention and exposes a lifecycle of created, bind, attached and detached hooks;[30] Aurelia 2 keeps the model with TypeScript decorators and interfaces.[31]

Reactivity and signals

The virtual DOM is not the only way to keep a page in step with its data. Solid (2018) compiles components to native DOM nodes instead of diffing a virtual tree, and updates them through fine-grained reactivity: a signal is a wrapper around an ordinary JavaScript value that keeps a list of subscribers notified whenever the value changes, and effects and derived signals subscribe automatically.[32] Angular adopted signals from version 16 (2023); by version 22 they cover signal, computed, effect, resources for asynchronous data, signal-based inputs and forms, and zoneless change detection, with a migration path from RxJS and NgRx.[33] A proposal to add signals to the language itself entered the TC39 process in 2024.

State management

As applications grew, their state moved out of components. Redux (2015) keeps all application state in one store and changes it only through actions handled by reducers; reducers are pure functions, with no side effects such as writing to localStorage or contacting a server, and they return a new state rather than mutating the old one.[34] That immutability is what makes change detection by reference comparison work, and it enables undo and "time travel" between versions of the state for debugging; libraries such as Immer and Immutable.js make the immutable updates less verbose.[34] A short, opinionated treatment reframes Redux as a front-end messaging system organised around actions and middleware.[35] Redux Toolkit (2019) later standardised the boilerplate.

Architecture at scale

Large front ends raise problems beyond any one component: normalising fetched data, paginating, debouncing search, rendering on the server, updating optimistically, syncing in real time and caching, which one source works through on a single Trello-style application alongside a framework for system-design interviews.[7] Large React applications also contend with data-fetching and state libraries, design systems, internationalisation, personalisation and A/B testing.[36] On the Angular side, strategic domain-driven design splits a system into domains and libraries whose boundaries are enforced with Nx and Sheriff, and micro frontends are deployed separately through Module Federation.[37] Nx itself is explained to Angular developers by mapping each Angular CLI command and workspace layout to its Nx equivalent.[38]

Beyond the browser

Node.js made JavaScript a general-purpose language, and the same runtime and package ecosystem now reach servers, phones, desktops, microcontrollers and factory floors.

Servers and Node.js

A Node.js server can be written from the built-in HTTP module alone, with routing, request handlers, POST handling and file uploads added by hand before any framework is involved.[39] Past that point the working vocabulary is npm, test-driven development, asynchronous control flow, event emitters, WebSockets and database drivers for MySQL and MongoDB.[4] Managed backends shift that work to a service: Firebase supplies authentication, a realtime database, Firestore, storage and cloud functions to React and Angular applications alike, with Angular consuming Firestore collections as observables.[40][41]

Mobile and desktop

JavaScript reaches phones two ways. React Native (2015) renders native iOS and Android components from React code and lets developers write native modules and UI components on both platforms when the bridge is not enough.[42] Hybrid frameworks run a web application inside a native shell: Ionic, built on Cordova and originally AngularJS, lets web developers use the knowledge they already have to build hybrid applications for iOS and Android, as against a fully native app or a mobile website.[43] On the desktop, Office add-ins for Excel, Word and OneNote are written against Office.js, whose asynchronous proxy-object model queues operations until context.sync() runs them.[44] Electron, which bundles Chromium with Node.js, is the usual route to desktop applications.

Hardware, games and industry

With the Johnny-Five library and the Firmata protocol, Node.js controls Arduino boards and sensors, and one source treats a hobby fire-alarm project as a software-engineering project with unit tests, continuous integration and coverage.[45] Multiplayer browser games pair an HTML5 client with a Node.js server for login, chat and game events.[46] In industrial settings Node.js speaks the OPC UA protocol through the Node-OPCUA library, with servers, clients, address spaces, subscriptions and certificates,[47] and Node-RED flows read Modbus devices with little or no code.[48] Security researchers script the Frida instrumentation toolkit in JavaScript or TypeScript to hook and trace compiled native programs.[49] Cloud infrastructure is declared in TypeScript with Pulumi, which turns ordinary programs into AWS resources,[50] and serverless applications on AWS Lambda are organised with domain-driven design in TypeScript.[51] Servers for the Model Context Protocol, which connects AI assistants to tools and data, are written in Node.js as readily as in Python or Java.[52]

Tooling

Shipping JavaScript to a browser means turning a tree of modules, styles and assets into a few optimised files, and keeping the code correct while it changes.

Bundlers and transpilers

webpack (2012) became the standard bundler of the 2010s. Its configuration grows from an entry point and an output through loaders for each file type and plugins, then into a development server, source maps, Babel and TypeScript, code and bundle splitting, minification, tree shaking, build analysis, server-side rendering and module federation.[53] Its early configuration was small enough to walk through option by option.[54] Babel (2014) transpiles new syntax for old browsers, and newer tools, Vite (2020) and esbuild, trade webpack's flexibility for speed.

Testing and debugging

Browser automation descends from Selenium and the WebDriver protocol; WebdriverIO drives real browsers from Node.js through browser drivers or the Chrome DevTools protocol, and one source insists that its real subject is when user-interface automation pays for itself and when skipping it is the better choice.[55] Visual regression testing compares screenshots against baseline images to catch unwanted design changes.[56] Within React, test-driven refactoring moves code from messy to well-structured through separation of concerns, custom hooks and composition.[57] For debugging, the Chrome DevTools panels, the browser debugger, the React, Angular and Redux DevTools extensions, performance APIs and front-end monitoring each have their place, and the DevTools MCP server lets an AI assistant drive them.[58]

Security

JavaScript runs untrusted on every visitor's machine, so its security is the browser's security. The attacks are well catalogued: cross-site scripting, where attacker-controlled text is executed as code, including the DOM-based variants; DOM clobbering, where named HTML elements shadow script variables; prototype pollution, where an attacker writes to Object.prototype and every object inherits the change; and bypasses of the same-origin policy that separates sites from one another. One source presents these from the researcher's side, with fuzzing, calling functions without parentheses and non-alphanumeric JavaScript as ways of finding and expressing them,[59] while another covers them within the wider web vulnerability classes of CORS and Content Security Policy bypasses, postMessage flaws and Node.js deserialisation.[60] The defences, escaping output, Content Security Policy, freezing prototypes and treating every message as hostile, are the responsibility of the application.

Sources

Every source is a Leanpub book or course. The note after each says which part of it was read; where no sample was available, only the public description and table of contents were used.

  1. 1.
    You Don't Know JS Yet: Get Started, Kyle Simpson: Get to know JS Free sample: preface and chapter 3, on iteration, closure, the this keyword and prototypes. Second edition, 2020. Free sample: PDF · EPUB
  2. 2.
    You Don't Know JS Yet: The Unbooks, Kyle Simpson: Previously Unpublished 2nd-Ed Book Content (Raw & Uncut) Free sample: preface and the object foundations chapters on properties, copying, descriptors and optional chaining. Unedited drafts, 2025. Free sample: PDF · EPUB
  3. 3.
    JavaScript Functions, Closures, and Prototypes, AJ Meyghani: Learn the fundamentals of functions, closures, and prototypes in JavaScript Description and table of contents: functions, closures, prototypes and interview questions. 2016.
  4. 4.
    The Node Craftsman Book, Manuel Kiessling: An advanced Node.js tutorial Free sample: the object-oriented JavaScript chapter, blueprints versus prototype links, with heap-snapshot measurements. 2017. Free sample: PDF · EPUB
  5. 5.
    Lodash 4 Cookbook, Fu Cheng: For lodash 4.17.21 Free sample: installation, common concepts and the collections chapter. lodash 4, 2025. Free sample: PDF · EPUB
  6. 6.
    The Beginners Guide To Node.js, Rick Hernandez: The practical guide to Node.js for new programmers Free sample: preface and front matter, including the book's list of topics (event loop, npm, versioning, installation). 2016. Free sample: PDF · EPUB
  7. 7.
    Frontend System Design Essentials, Juntao Qiu: A practical guide to designing scalable, reliable, and maintainable frontend systems. Free sample: preface and chapters 1 and 2, the user-select dropdown from a happy-path fetch to debouncing and AbortController, and the interview framework. 2026. Free sample: PDF · EPUB
  8. 8.
    The NodeJS Cluster Module, Antonio Santiago Description and table of contents: the cluster module, PM2 and graceful shutdown. 2017.
  9. 9.
    Understanding JavaScript RegExp, Sundeep Agarwal: Example based guide to mastering JavaScript regular expressions Free sample: preface and the opening chapters on the RegExp object, flags, anchors, alternation, grouping and escaping. 2023. Free sample: PDF · EPUB
  10. 10.
    SurviveJS - Maintenance, Juho Vepsäläinen, Artem Sapegin: Streamline JavaScript Workflow Description and table of contents: packaging, code quality, infrastructure, documentation and the future of a project. 2021.
  11. 11.
    Functional-Light JavaScript, Kyle Simpson: Balanced, Pragmatic FP in JavaScript Free sample: preface and chapter 4, Composing Functions, on compose, pipe, partial application and point-free style. 2018. Free sample: PDF · EPUB
  12. 12.
    Unwrapping Monads & Friends, Kyle Simpson: Shining Light on Functional Programming's Scariest Concepts Free sample: introduction, chapter 2 on monads as a pattern, the Identity monad, functors and the monad laws, and the wrap-up. 2025. Free sample: PDF · EPUB
  13. 13.