Second-Draft Verification Note (2026-10-15): This is the second draft of the HeLuoXu tutorial, revised against official specifications and documentation. Legacy experiment logs are labeled separately as "First-Draft Retained Output" and do not represent a re-run on Windows in this pass; see the current batch verification records for the environment and results of this pass. Examples such as "StarRiver Notes", accounts, orders, prices, and policies are fictional teaching data.
One-Sentence Definition
JavaScript is a dynamic language whose core semantics are defined by the ECMAScript specification and executed across hosts such as browsers and Node.js. A single JavaScript execution agent typically schedules work via an event loop, while Workers can run on separate threads and browsers also execute WebAssembly.
Why It Matters
- Modern frontend frameworks and interactive web interfaces are built with JavaScript; chat UIs and streaming response renderers in AI applications all rely on JS.
- The Node.js package landscape offers a rich set of AI SDKs and Agent frameworks (such as the Vercel AI SDK and LangChain.js).
- Several counter-intuitive mechanics in JavaScript (the event loop, IEEE 754 number precision, and implicit type coercion) are frequent sources of production bugs—we will verify each of them with runnable code below.
How It Works / Diagram
ECMAScript Language Specification: https://tc39.es/ecma262/; Event Loops in the HTML Standard: https://html.spec.whatwg.org/multipage/webappapis.html#event-loops; MDN JavaScript Guide: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide; Node.js Event Loop Guide: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick
Key Takeaway: Within a single execution agent, only one task runs at a time (Workers can execute separately); "asynchronous" means non-blocking while waiting for I/O or timers, not multi-core parallel computation. A long synchronous computation freezes the page and delays all queued callbacks.
Applicable Boundaries & Verification Points
Browser task queues and the Node.js libuv event loop are not identical schedulers. The diagram explains the relative ordering of Promises and timers in our example and does not guarantee a universal ordering across all I/O callbacks, process.nextTick, and setImmediate in every execution context. Concurrency via Promise.all is not multi-core CPU parallelism, nor does it automatically rate-limit requests or cancel sibling requests when one fails. Alongside Number, JavaScript provides BigInt; however, precision already lost during JSON.parse cannot be recovered afterward by wrapping the rounded number in BigInt(number). The regex extraction shown below is strictly for fixed-format demonstration—production APIs should serialize 64-bit integer IDs as strings.
Primary references verified in this pass (2026-10-15):
- MDN: Execution Model: execution agents, jobs, and Workers.
- Node.js: The Event Loop, Timers, and process.nextTick(): Node event loop phases and timer scheduling.
Runnable Example
This script runs under Node.js to test the event loop, closures, floating-point precision, and concurrent async awaiting. The Node 20 version and timings shown in the retained log come from the first-draft environment; task ordering across different hosts and contexts should be verified on the target runtime.
// File: examples/web/17_javascript.mjs
// Core JavaScript mechanics experiment: event loop, closures, number precision, large-integer JSON, type coercion, and concurrent await.
console.log("Node", process.version);
console.log("1. Event loop: synchronous code -> microtasks (Promise) -> macrotasks (setTimeout)");
const order = [];
setTimeout(() => order.push("setTimeout 0"), 0);
Promise.resolve().then(() => order.push("Promise.then"));
queueMicrotask(() => order.push("queueMicrotask"));
order.push("synchronous code");
await new Promise(r => setTimeout(r, 10));
console.log(" Execution order:", order.join(" -> "));
console.log("2. Closures and var vs. let");
const fv = [], fl = [];
for (var i = 0; i < 3; i++) fv.push(() => i);
for (let j = 0; j < 3; j++) fl.push(() => j);
console.log(" var:", fv.map(f => f()), " let:", fl.map(f => f()));
console.log("3. All Number values are IEEE 754 double-precision floats (including integers)");
console.log(" 0.1 + 0.2 =", 0.1 + 0.2, "| === 0.3 ?", 0.1 + 0.2 === 0.3);
console.log(" Number.MAX_SAFE_INTEGER =", Number.MAX_SAFE_INTEGER);
const raw = '{"id": 1849302847561928374, "tokens": 12}';
console.log(" JSON.parse large integer id:", JSON.parse(raw).id, "<- trailing digits were silently rounded");
console.log(" Manual extraction with BigInt:", BigInt(raw.match(/"id": (\d+)/)[1]).toString());
console.log("4. Implicit type coercion in loose equality ==");
for (const [a, b] of [["0", 0], ["", 0], [null, undefined], [[], false], ["1", true]])
console.log(` ${JSON.stringify(a)} == ${JSON.stringify(b)} -> ${a == b} ===: ${a === b}`);
console.log("5. async/await: sequential vs. concurrent (simulating three 200ms API calls)");
const call = (n) => new Promise(r => setTimeout(() => r(n), 200));
let t = performance.now(); for (const n of [1, 2, 3]) await call(n);
console.log(` for...await sequential: ${(performance.now() - t).toFixed(0)} ms`);
t = performance.now(); await Promise.all([1, 2, 3].map(call));
console.log(` Promise.all concurrent: ${(performance.now() - t).toFixed(0)} ms`);
console.log("6. A 300ms synchronous busy-loop blocks all timers");
t = performance.now(); let fired;
setTimeout(() => { fired = performance.now() - t; }, 10);
const end = performance.now() + 300; while (performance.now() < end) {}
await new Promise(r => setTimeout(r, 20));
console.log(` Timer scheduled for 10ms actually fired after ${fired.toFixed(0)} ms`);
First-Draft Retained Output
The following log is retained from the first draft and reflects the original environment claimed there; it is not the re-run output of this pass. Second-draft code edits may produce different output; refer to the current batch verification records for the actual re-run status.
Node v20.19.2
1. Event loop: synchronous code -> microtasks (Promise) -> macrotasks (setTimeout)
Execution order: synchronous code -> Promise.then -> queueMicrotask -> setTimeout 0
2. Closures and var vs. let
var: [ 3, 3, 3 ] let: [ 0, 1, 2 ]
3. All Number values are IEEE 754 double-precision floats (including integers)
0.1 + 0.2 = 0.30000000000000004 | === 0.3 ? false
Number.MAX_SAFE_INTEGER = 9007199254740991
JSON.parse large integer id: 1849302847561928400 <- trailing digits were silently rounded
Manual extraction with BigInt: 1849302847561928374
4. Implicit type coercion in loose equality ==
"0" == 0 -> true ===: false
"" == 0 -> true ===: false
null == undefined -> true ===: false
[] == false -> true ===: false
"1" == true -> true ===: false
5. async/await: sequential vs. concurrent (simulating three 200ms API calls)
for...await sequential: 602 ms
Promise.all concurrent: 203 ms
6. A 300ms synchronous busy-loop blocks all timers
Timer scheduled for 10ms actually fired after 301 ms
- 1. The execution order is
synchronous code -> Promise.then -> queueMicrotask -> setTimeout 0: even with a0ms delay, macrotasks wait until the entire microtask queue drains. BothPromise.thenandqueueMicrotaskenqueue into the microtask queue in registration order. - 2. Because
varis function-scoped, all three closures share a single bindingiwhose value is3after the loop ends;letcreates a fresh block-scoped binding per iteration, yielding0, 1, 2. Preferletandconstin new code while understanding how legacyvarbindings behave. - 3.
0.1 + 0.2evaluates to0.30000000000000004. Even more dangerous in web apps are 64-bit integers: any ID exceedingNumber.MAX_SAFE_INTEGER(9007199254740991, i.e., 2^53 - 1) is silently rounded byJSON.parse—turning1849302847561928374into1849302847561928400and corrupting database primary keys or Snowflake IDs in the frontend. Mitigation: serialize 64-bit integer IDs as strings in your API, or parse raw JSON text with aBigInt-aware parser (MDNNumber.MAX_SAFE_INTEGER: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). - 4. Loose equality (
==) performs implicit type coercion so[] == falseand"" == 0both evaluate totrue; strict equality (===) evaluates tofalsefor every pair. - 5. Across three independent 200 ms requests, a sequential
for...awaitloop takes ~602 ms whereasPromise.allcompletes in ~203 ms—independent I/O calls can be issued concurrently within your rate-limit, cost, and cancellation constraints. - 6. A 300 ms synchronous busy-loop delays a 10 ms timer until ~301 ms. In a browser, that freezes the UI for 300 ms; in a Node.js worker process, it blocks every concurrent request and callback sharing that execution agent (the exact same pitfall as calling a synchronous blocking function inside an
async defendpoint in k6.web.fastapi).
Self-Test
Question: If you run const parsed = JSON.parse(raw) first and then pass BigInt(parsed.id), can you recover the original 64-bit integer ID sent by the server?
Reference Answer: No. IEEE 754 rounding has already occurred during JSON.parse. Have the API transmit 64-bit IDs as strings, or use a JSON parser that exposes the raw numeric token before float conversion; do not rely on a simple regular expression as a general-purpose JSON parser.
Common Misconceptions
- "JavaScript is related to Java": Aside from the marketing name and superficial C-style syntax, the two languages are unrelated.
- "An
asyncfunction runs on a background thread": No—it runs on the same execution thread and only yields control atawaitpoints. Offload CPU-heavy work to Web Workers or Node.jsworker_threads(https://nodejs.org/api/worker_threads.html). - "
setTimeout(fn, 0)executes immediately": As shown in steps 1 and 6, it waits for the current synchronous turn, all queued microtasks, and any blocking work on the event loop. - "JSON numbers have identical precision across backend and frontend": As shown in step 3, the JSON specification (RFC 8259 Section 6: https://www.rfc-editor.org/rfc/rfc8259#section-6) sets no limit on numeric precision, but JavaScript's
JSON.parsemaps numbers to IEEE 754 double-precision floats.
Connection to AI Development
- When rendering streaming LLM responses in the browser, read SSE chunks via
fetch+ReadableStreamorEventSourceand append text incrementally; assign totextContentrather thaninnerHTMLto prevent XSS (see k6.web.html). - Token counts and logprobs easily fit inside safe integer bounds, but conversation IDs and message IDs generated as 64-bit Snowflake integers must be serialized as strings.
- When running small models directly in the browser via WebGPU or WebAssembly (for example, with
transformers.js), execute inference inside a Web Worker so the main UI thread stays responsive (https://huggingface.co/docs/transformers.js).
Further Reading
- The Modern JavaScript Tutorial: https://zh.javascript.info/
- MDN Concurrency Model and the Event Loop: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Event_loop
- For the JavaScript/TypeScript toolchain (package managers, runtimes, and build tools), see k6.lang.js-ts-toolchain.
Unverified Scope
- Does not exhaustively test ordering across all Node.js event-loop phases,
process.nextTick, andsetImmediatecontexts, nor does it test concurrency rate-limiting against a live external API.
Current Example Execution Scope
2026-10-15: Passed. Executed locally with Node.js and locked dependencies; DOM demonstrations use jsdom without a real browser layout engine.
"First-Draft Retained Output" preserves the original text and is not newly generated by the second-draft code; its original conclusions must be read together with the second-draft revisions and boundary notes.
Companion Code & Verification Materials