Tag
javascript
Published articles tagged javascript.
A short history of JavaScript
JavaScript began as a ten-day prototype in a browser and became the shared runtime of the web, servers, and tools. This overview follows that arc from Netscape in 1995 through ECMAScript, Node.js, transpilers, and today's yearly language releases.
Accepting payments with Stripe Checkout
Stripe Checkout hosts the payment UI on Stripe's domain: your server creates a Session, the browser redirects, and webhooks confirm the sale. This runbook wires Checkout into Express for one-time Prices with success and cancel pages.
Async iterators and for await..of
Async iterables produce values that may arrive after await, which fits streams, paginated APIs, and backpressure-friendly pipelines. This chapter covers Symbol.asyncIterator, async generators, and for await..of consumption.
Async/await in JavaScript
Async functions always return a Promise, and await pauses until a Promise settles—giving sequential async code without nested then chains. This chapter covers syntax, parallel awaits, and error handling patterns.
Breaking up long tasks
A page that ignores clicks for a moment, a spinner that never appears, or a poor Interaction to Next Paint score usually has one cause: a single task holding the main thread. This page shows how to confirm it, why await alone does not help, and the three fixes — yield, defer, or move the work.
Callbacks and timers
Host APIs still expose completion handlers as functions you pass in. This chapter covers callback conventions, setTimeout and setInterval, and why nested callbacks led to promises and async/await.
Cancellation with AbortController
Promises do not cancel themselves; AbortController provides a standard signal for fetch, streams, and your own async tasks. This chapter covers signals, abort reasons, and cleaning up listeners when work is no longer needed.
Classes in JavaScript
class syntax is mostly syntactic sugar over prototypes: constructors install own state, methods live on the prototype, extends wires the chain. Fields, private #members, and static blocks match what Java or C# developers expect with a few JavaScript-specific rules.
Concurrency with workers
Workers are how JavaScript runs in parallel: each one is a separate thread with its own heap and event loop, talking to the others through messages. This chapter covers starting workers in browsers and Node, what copying, transferring, and sharing memory each cost, and which kind of worker fits which job.
Control flow in JavaScript
if and switch follow C-shaped syntax, but switch uses strict equality and falls through unless you break. Labeled break and continue apply to any statement, not only loops—a feature most statically typed languages omit. Ternary expressions fill the same niche as other languages’ inline conditionals.
Custom payment forms with the Payment Element
When Checkout's hosted page is not enough, embed the Payment Element: your server creates a PaymentIntent, the browser mounts Stripe.js UI, and confirmPayment finishes authentication. This runbook compares that path with Checkout for Express apps.
Customers in Stripe
A Stripe Customer is the billing profile for someone in your app: email, metadata, and saved payment methods. This chapter shows how to create customers at signup, map them to your user ids, and save cards for on-session and off-session charges with SetupIntents.
Data types in JavaScript
ECMAScript divides values into seven primitives and Object. typeof is the everyday type check, but it has well-known holes. This overview maps the type system and points to chapters on copying, coercion, numbers, strings, and symbols.
Dates and Temporal
Date has been the built-in clock since ES1, but mutability and time-zone gaps push new code toward Temporal. This comparison covers what Date still does, what Temporal fixes, and how to choose in browsers and Node today.
Destructuring and spread
Destructuring unpacks arrays and objects into bindings; spread copies iterables and expands objects in literals. Together they replace much of the manual indexing common in Java or Go. Rest in patterns collects leftovers without the arguments object.
ECMAScript versions cheat sheet
Each yearly ECMAScript edition bundles finished proposals. This cheat sheet lists headline additions from ES5 through recent editions so you can map syntax you see in tutorials to the standard that introduced it.
Execution contexts and the call stack
Every running piece of code has an execution context that says where its variables are, what this is, and which realm's built-ins it sees. This chapter follows contexts onto and off the call stack, explains hoisting, closures, suspension, and realms in those terms, and shows how to read the stack traces that come out of it.
Finding memory leaks
A JavaScript leak is memory the program can still reach but will never use again. This page is the procedure for finding one: confirm the growth survives garbage collection, use heap snapshots to find what is retained and by what, then fix the reference. It ends with the causes behind most leaks.
From source code to machine code
An engine has to start running code within milliseconds and still end up with fast machine code for the functions that matter. This chapter follows a function through V8's parser, interpreter, and three compilers, shows how type feedback drives optimization, and explains why optimized code gets thrown away.
Functional patterns in JavaScript
IIFEs isolate scope before modules were universal; currying, compose, and memoize express reusable function plumbing. JavaScript is multi-paradigm—these patterns are idiomatic where they reduce noise, not mandatory style.
Functions in JavaScript
Functions are first-class values: declarations hoist differently from const bindings, arrow functions inherit lexical this, and the rest parameter replaces most uses of the arguments object. Default parameters run at call time and can reference earlier parameters—unlike overload sets in Java or C#.
Hidden classes and inline caches
In the language, an object is a bag of named properties that can change at any time. Engines make property access fast anyway by giving objects hidden shapes and caching what each access site has seen. This chapter shows how shapes form, what breaks them, how arrays get the same treatment, and how to check it yourself.
Higher-order functions and callbacks
Functions are first-class values: pass them as arguments, return them, store them in data structures. Array methods and async APIs build on that model— familiar if you have used map/filter in Python or streams in Java.
How ECMAScript is standardized
ECMAScript is maintained by TC39 at Ecma International. Proposals move through numbered stages, are validated by test262, and ship as yearly editions — separate from HTML, fetch, and other host specifications.
Internationalization with Intl
Intl formats numbers, dates, lists, and plural messages using locale data built into the engine—without shipping your own locale files for common cases. This page maps the main constructors and when to reach for each.
Iterator helpers
ES2025 adds lazy iterator objects with map, filter, take, and related helpers so you can chain sequence operations without copying arrays. This chapter covers Iterator.from, chaining, and when helpers beat array methods.
JavaScript engine glossary
The Under the Hood series uses terms from three sources: the ECMAScript specification, the HTML Standard's event loop, and the engines' own documentation. This glossary defines each of them in a sentence or two, grouped by topic, and links to the chapter that explains it.
JavaScript syntax at a glance
JavaScript blurs the line between statements and expressions more than C-style languages do, and parsers apply automatic semicolon insertion when you omit terminators. This chapter maps strict mode, script versus module goals, and the syntactic habits that surprise newcomers from Java, Go, or Python.
JSON in JavaScript
JSON.parse and JSON.stringify are the built-in bridge between JavaScript values and UTF-8 text. This page covers syntax limits, revivers/replacers, and safe parsing—plus where jq fits when JSON lives in shell pipelines.
Loops in JavaScript
for-of iterates values; for-in walks enumerable keys and is the wrong default for arrays. Classic for loops with var still show up in legacy code and create closure bugs in callbacks. break, continue, and labels behave like C, with for-await-of added for async iterables.
Map and WeakMap
Map and WeakMap associate keys with values when object identity or garbage collection behavior matters more than string property names. This page compares APIs, iteration, and typical use cases next to plain objects and Set.
Memory management and garbage collection
JavaScript gives you no way to free memory, only ways to stop referring to it. This chapter explains what the heap holds, how a tracing collector decides what is garbage, why V8 splits the heap into generations, how heap limits and weak references work, and why cleanup of files and sockets cannot be left to the collector.
Numbers and BigInt in JavaScript
JavaScript numbers are IEEE-754 double-precision values with a safe integer range and familiar binary rounding surprises. BigInt stores arbitrary integers but cannot mix with number in arithmetic without an explicit conversion. This chapter covers literals, safety checks, and when to use each type.
Objects in JavaScript
Plain objects are string-keyed maps with a prototype chain, not fixed structs like C structs or Java POJOs. Literals, property access, shorthand, computed keys, and references versus copies set the baseline for everything else in this series.
Operators in JavaScript
Beyond familiar arithmetic and comparison, JavaScript adds nullish coalescing, optional chaining, and logical assignment operators that behave differently from || and && in other languages. Precedence tables from C do not fully apply; this page covers the operators that change control flow and defaulting logic.
Products and prices in Stripe
Products describe what you sell; Prices say how much and how often. Prices are immutable, so catalog changes mean new Price objects. This chapter covers one-time and recurring prices, lookup keys, and seeding a catalog from Node.js.
Promises in JavaScript
A Promise represents one eventual result—fulfilled or rejected—and gives shared combinators for sequencing and racing async work. This chapter covers construction, then/catch/finally, Promise.all, and common pitfalls.
Prototypes and inheritance
JavaScript links objects through prototypes, not class tables copied at compile time. Property lookup walks the chain; methods live on shared prototype objects—similar in spirit to Ruby modules, unlike Java subclass field layout.
Proxy and Reflect
Proxy wraps an object and intercepts get, set, and other operations— validation, logging, reactivity, and virtual properties. Reflect mirrors those operations as functions for consistent defaults in traps.
Freezing and sealing objects
Object.preventExtensions, seal, and freeze tighten what can change on an object—useful for config snapshots and defensive copies, not deep immutability.
Regular expressions in JavaScript
RegExp matches patterns in strings—literals, flags, groups, and common String methods. This page summarizes syntax and API surface, including modern named groups and the RegExp.escape helper from recent editions.
Scope and closures
Lexical scope decides which bindings are visible where; closures keep outer variables alive after the outer function returns. If you know block scope from C#, Java, or Rust, JavaScript's var hoisting and function closures are the pieces that differ most.
Strings and template literals in JavaScript
JavaScript strings are immutable sequences of UTF-16 code units, not full Unicode code points. Template literals add interpolation, multiline text, and tagged functions. This chapter covers creation, indexing, iteration, and common Unicode pitfalls.
Stripe API keys and the Node.js SDK
Publishable keys belong in the browser, secret and restricted keys stay on the server, and every call goes through a Stripe client instance. This chapter shows how to wire the official stripe npm package into Express, pin an API version, and handle idempotency and errors safely.
Stripe beyond payments
Checkout and subscriptions cover most SaaS needs, but Stripe also runs marketplaces, tax, fraud tools, invoicing, in-person Terminal, and identity checks. This overview names each product so you know what to reach for next without duplicating Stripe's full documentation.
Stripe cheat sheet
Commands and API calls you reach for daily when integrating Stripe with Node.js: CLI forwarding, test cards, key prefixes, and stripe-node snippets grouped by object. Use with the narrative chapters when you need a quick lookup.
Subscriptions in Stripe
Subscriptions bill Customers on a recurring Price, generate Invoices, and change state over time. This chapter uses Checkout in subscription mode, syncs access through webhooks, and touches upgrades, trials, and the Customer Portal.
Symbols in JavaScript
A symbol is a unique, immutable primitive used as a property key that will not collide with string keys or other libraries. Well-known symbols customize built-in behavior. This chapter covers creation, registry symbols, and where symbols show up in everyday APIs.
The event loop, tasks, and microtasks
The event loop is what turns one thread into a responsive program: it picks a task, runs it to completion, drains the microtasks, and gives the browser a chance to render. This chapter walks one turn of the loop, predicts the output of ordering puzzles from first principles, and shows where Node's loop differs.
The this keyword
this is not lexical like most variables—it is set when a function runs. Call site, method syntax, bind/call/apply, arrow functions, and classes each follow rules that differ from Python's self or Java's implicit receiver.
Type coercion and equality in JavaScript
Operators and built-ins convert operands when types do not match. Loose equality runs a long conversion pipeline; strict equality compares type and value without coercion. This chapter maps the rules that explain surprising console output.
Typed arrays and ArrayBuffer
Typed arrays view raw bytes in an ArrayBuffer as integers or floats—used by WebGL, audio, binary protocols, and WASM interop. This page explains buffers, views, endianness, and how they differ from normal JavaScript arrays.
Variables and declarations
Three declaration keywords—var, let, and const—interact with hoisting and the temporal dead zone in ways that differ from block-scoped languages like Java or Rust. const only freezes the binding, not deep object contents. This chapter is the reference for choosing among them in modern code.
Webhooks in Stripe
Webhooks deliver signed Event objects when payments and subscriptions change. Your Express handler verifies signatures, stays idempotent, and fulfills orders there—not on the success page. This chapter covers routing, key events, and local testing with the Stripe CLI.
What is Astro
Astro renders pages to HTML on the server and ships JavaScript only for the components that need it. This overview explains the islands model, the kind of site Astro is built for, how the project got here, and when another framework is the better choice.
What is GraphQL
GraphQL is a typed query language for APIs: clients describe the shape of the data they need, and the server returns JSON that matches. This overview covers how requests flow from parse to execution, how responses differ from REST, and when a GraphQL layer is worth the complexity.
What is Stripe?
Stripe sits between your web application, your server, and the card networks: it stores customers and catalog data, runs Checkout or custom payment flows, and notifies your backend through webhooks. This overview maps the main API objects and test environments before you write integration code.
pnpm
pnpm keeps one copy of each dependency file and links it into every project that needs it. This page explains that layout, how it compares with npm, Yarn, and Bun, and the commands you run day to day.
Yarn
Yarn keeps one zip of each package and, by default, points Node at those zips instead of copying them into node_modules. This page explains that layout, how it compares with npm, pnpm, and Bun, and the commands you run day to day.
Module interoperability
This articles gives an overview about how the different modules systems can or cannot be used together.
Testing TypeScript with Jest
Refer to https://jestjs.io/docs/getting-started
Decorators in TypeScript
TypeScript decorators are a way to modify or extend the behavior of classes, methods, or properties in a declarative manner. They are denoted by the @ symbol and are applied using a syntax similar to…
A quick introduction to modules
JavaScript uses several module systems in the wild — CommonJS, ESM, and legacy AMD/UMD — each shaped by its host. This introduction maps those systems before the deeper chapters in the JS Modules series.
Defining object properties in JavaScript
Object.defineProperty and friends attach data or accessor descriptors with explicit writable, enumerable, and configurable flags—closer to Java Bean descriptors than to a simple field assignment.
SinonJS with Mocha
Fakes, spies and stubs are created in the default sandbox which needs to be restored after each test to prevent memory leaks. We use a Mocha hook plugin for that:
The concepts of testing
When it comes to speaking how many tests there should be for each test type then you can assume that you will write mostly Unit Tests, a moderate amount of Integration Tests and a relatively small…
Error handling in JavaScript
JavaScript has no compile step in the browser: syntax fails at parse time, everything else surfaces at runtime through throw and the Error hierarchy. try/catch/finally, the cause option, custom Error subclasses, and AggregateError cover sync code and Promise rejection paths.
JavaScript Fails
JavaScript will look you in the eye and insist that these results are normal. NaN is a number, 0.1 + 0.2 is not 0.3, and two empty arrays added together become a string. This page keeps each famous expression, the value it produces, and the rule that makes the despair official.
Set in JavaScript
A Set stores unique values using SameValueZero equality—handy for deduplication, membership tests, and set algebra. This page covers construction, iteration, and the native union/intersection helpers added in ES2025.
Filter object properties by key
Pick or drop keys on a plain object without mutating the original—destructuring for one key, Object.fromEntries with filter for allowlists.
Testing JavaScript NodeJS files with Mocha and Chai
This article will demonstrate how to test JavaScript files in NodeJS using the libraries Sinon, Mocha and Chai. Sinon is often installed together with Mocha and Chai, but it is not required.
Pass by value and reference in JavaScript
Primitives are copied by value; objects are shared by copying a reference to the same identity. Reassigning a binding is not the same as mutating an object. This chapter explains what actually moves when you pass arguments or assign to another variable.
Async and defer loading of JavaScript
Classic script tags block HTML parsing while they download and run. The async and defer attributes change when download and execution happen relative to the document, and module scripts follow different rules again.
Arrays in JavaScript
Arrays are ordered, indexable lists and the default collection in most JavaScript code. This cheat sheet groups creation, mutation, search, and higher-order methods—including ES2023 non-mutating updates—so you can scan the API without rereading a tutorial.
Generators in JavaScript
Generator functions pause at yield and resume on next(), which makes them the standard way to build iterators without manual state. This chapter covers two-way yield, for..of, yield*, and early completion with return and throw.
Iterators in JavaScript
Iterators expose a uniform way to walk values one step at a time, whether the source is an array, a map, or a custom sequence. This chapter covers the iterator and iterable protocols, for..of, and when manual next() beats a loop.
JavaScript under the hood
Your code runs inside an engine, the engine runs inside a host, and the host decides when your code runs at all. This overview maps those layers, follows one small program through all of them, and points to the chapter that takes each layer apart.
Asynchronous data handling
JavaScript runs user code on one thread per realm, yet programs must respond to timers, network I/O, and user input without blocking. This overview maps callbacks, promises, async/await, cancellation, and observables—and when each fits.
Observing element changes with MutationObserver in JavaScript
MutationObserver runs a callback after the DOM changes — attributes, child nodes, or text — without polling. This page shows how to configure observation narrowly so you pay only for the mutations you care about.
Observables in JavaScript
Observables push many values over time and support unsubscribe, which suits events and live streams but adds weight promises avoid. This comparison chapter covers push versus pull, RxJS basics, and when to stay with promises.