<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by NodalDOT on Medium]]></title>
        <description><![CDATA[Stories by NodalDOT on Medium]]></description>
        <link>https://medium.com/@nodaldot?source=rss-431fae6dd776------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*10amzJMrRlVKfQQilg7G5A.jpeg</url>
            <title>Stories by NodalDOT on Medium</title>
            <link>https://medium.com/@nodaldot?source=rss-431fae6dd776------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:22:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nodaldot/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Promises Work: Building a Promise Core in TypeScript]]></title>
            <link>https://medium.com/@nodaldot/how-promises-work-building-a-promise-core-in-typescript-cccf9313b771?source=rss-431fae6dd776------2</link>
            <guid isPermaLink="false">https://medium.com/p/cccf9313b771</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[NodalDOT]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 00:00:07 GMT</pubDate>
            <atom:updated>2026-11-25T20:56:58.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="JavaScript Promise example showing the console output in order: “before”, “executor”, “after”, then 42." src="https://cdn-images-1.medium.com/max/1024/1*GsPNMNBEemMDNQrsleswEw.png" /></figure><h4>Build a minimal Promise implementation and see how executors, microtasks, chaining, and thenables fit together.</h4><p>I love digging through source code. I like it even more when something looks simple at first and turns out to have more going on. Take promises. You’ve probably heard the interview question “What is a Promise?” It’s a way to represent an operation that will eventually succeed or fail. What could be so complicated about that?</p><p>Then you open the spec and find that the function you pass to new Promise runs synchronously. It even has a name in the spec: the <strong>executor</strong>. A then handler, on the other hand, always runs later, even when the result is already available. And if that handler returns an object with a callable then method, the next promise follows that object&#39;s outcome.</p><p>If any of that surprised you, keep reading. If it all sounds familiar, let’s use it to build our own Promise. We’ll follow the <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-objects">ECMAScript specification</a> along the way.</p><h3>Promise states</h3><p>A promise has three possible states:</p><ul><li><strong>pending</strong> — the outcome is still unknown.</li><li><strong>fulfilled</strong> — the promise has a fulfillment value.</li><li><strong>rejected</strong> — the promise has a rejection reason.</li></ul><p>A promise is <strong>settled</strong> once it’s either fulfilled or rejected. From then on, its state and result stay the same.</p><p>Here’s one way to model that in TypeScript:</p><pre>type PromiseState&lt;T&gt; =<br>    | { status: &quot;pending&quot; }<br>    | { status: &quot;fulfilled&quot;; value: T }<br>    | { status: &quot;rejected&quot;; reason: unknown };</pre><p>This TypeScript type is our model for the article. ECMAScript uses two internal slots: [[PromiseState]] for the state and [[PromiseResult]] for the fulfillment value or rejection reason. Internal slots are part of how the spec describes an object. You can&#39;t read them as ordinary properties.</p><h3>The executor and the result</h3><p>Let’s look at what runs when. This example follows the <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-executor">Promise constructor algorithm</a>:</p><pre>console.log(&quot;before&quot;);<br>const promise = new Promise((resolve) =&gt; {<br>    console.log(&quot;executor&quot;);<br>    resolve(42);<br>});<br>promise.then((value) =&gt; console.log(value));<br>console.log(&quot;after&quot;);<br>// before<br>// executor<br>// after<br>// 42</pre><p>The executor runs as part of creating the promise. The then handler runs later, even though the promise is already fulfilled when we attach the handler. That&#39;s why 42 appears after &quot;after&quot;.</p><p>The executor can be a named function. The constructor passes it two functions, resolve and reject. You call resolve with a value or a thenable, and reject with a rejection reason. If the executor throws before calling either function, the promise is rejected with the thrown value.</p><p>Calling resolve doesn&#39;t always fulfill the promise right away. If you pass it an object with a callable then, including a built-in promise, your promise follows that object&#39;s outcome. An object like this is called a <strong>thenable</strong>. Once either resolve or reject has been called, any later calls to that pair have no effect.</p><h3>A look at the spec</h3><p>Take a deep breath. 🙂 Here’s a quick look at the <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-properties-of-promise-instances">internal slots of Promise instances</a>:</p><pre>[[PromiseState]]: pending | fulfilled | rejected<br>[[PromiseResult]]: fulfillment value or rejection reason<br>[[PromiseFulfillReactions]]: fulfillment reactions<br>[[PromiseRejectReactions]]: rejection reactions<br>[[PromiseIsHandled]]: whether the promise has been marked as handled</pre><p>The slot names and states come from the spec. The descriptions are shortened. Reactions record what should happen when a promise settles. For example, when you pass fulfillment and rejection handlers to then, those handlers need to run at the right time.</p><p>You can breathe again. Let’s see how some of those slots translate into fields on our own class.</p><h3>Building our own promise</h3><p>We’ll call the class PromiseCore, after the <a href="https://nodaldot.github.io/toolkit/?item=vanilla%2Finternals%2FpromiseCore">implementation in toolkit</a> we&#39;ll use as a reference.</p><p>TypeScript gives us a starting point in its standard library declarations. The PromiseLike&lt;T&gt; interface describes a promise-like object with a then method. That method accepts fulfillment and rejection handlers and returns a new PromiseLike whose value type reflects what the handlers return.</p><pre>export class PromiseCore&lt;T&gt; implements PromiseLike&lt;T&gt; {<br>    // The state, constructor, and then method will go here.<br>}</pre><p>T is the type of the fulfillment value. For example, the fulfillment handler for a PromiseCore&lt;number&gt; receives a number. The implements clause asks TypeScript to check that our class has a compatible then method. We still have to write that method ourselves. Until we do, this sketch won&#39;t type-check.</p><p>PromiseLike is enough for what we&#39;re building here: a promise core that can chain through then. To resolve a promise with an object, ECMAScript looks up the object&#39;s then property at runtime. The spec also has a separate operation, IsPromise, for cases that require identifying a built-in Promise instance.</p><p>First, the class needs somewhere to store its result and the reactions waiting for it.</p><pre>type PromiseStatus = &quot;pending&quot; | &quot;fulfilled&quot; | &quot;rejected&quot;;<br>const PENDING: PromiseStatus = &quot;pending&quot;;<br>type Reaction = (result: unknown) =&gt; void;<br><br>// Fields inside PromiseCore&lt;T&gt;<br>#status: PromiseStatus = PENDING;<br>#result: unknown = undefined;<br>#fulfillReactions: Reaction[] = [];<br>#rejectReactions: Reaction[] = [];</pre><p>A new promise starts out pending. We initialize #result to undefined. The status is what tells us whether a result is available, since a fulfilled promise can also hold undefined. The two arrays store fulfillment and rejection reactions. The # prefix makes these fields private, so code outside the class can&#39;t access them directly.</p><h3>Checking the executor</h3><p>The built-in Promise constructor throws a TypeError if the executor isn&#39;t callable. Here&#39;s the relevant step in the <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-executor">constructor algorithm</a>:</p><pre>If IsCallable(executor) is false, throw a TypeError exception.</pre><p>IsCallable checks whether the value can be called.</p><p>In TypeScript, we can describe the functions the constructor passes to the executor:</p><pre>type Resolve&lt;T&gt; = (resolution: T | PromiseLike&lt;T&gt;) =&gt; void;<br>type Reject = (reason?: unknown) =&gt; void;<br>type Executor&lt;T&gt; = (resolve: Resolve&lt;T&gt;, reject: Reject) =&gt; void;<br><br>// Inside PromiseCore&lt;T&gt;<br>constructor(executor: Executor&lt;T&gt;) {<br>    if (typeof executor !== &quot;function&quot;) {<br>        throw new TypeError(&quot;Executor must be a function&quot;);<br>    }<br>    const { resolve, reject } = this.#createResolvingFunctions();<br>    try {<br>        executor(resolve, reject);<br>    } catch (error) {<br>        reject(error);<br>    }<br>}</pre><p>TypeScript can catch an invalid argument at compile time. The types are erased at runtime, and plain JavaScript can call the class too. That’s why the constructor needs its own check.</p><p>Next we create resolve and reject, then call the executor immediately with both functions. The try...catch passes anything the executor throws to reject. If the executor has already called either function, that later call to reject must have no effect.</p><p>#createResolvingFunctions handles the value passed to resolve and makes sure only the first call to the pair counts.</p><h3>Where resolve and reject come from</h3><p>We’re used to having these functions handed to us:</p><pre>new PromiseCore&lt;number&gt;((resolve, reject) =&gt; {<br>    resolve(42);<br>    // Or reject(new Error(&quot;Something went wrong&quot;));<br>});</pre><p>Now that we’re writing the promise ourselves, we have to create the functions too. #createResolvingFunctions returns a { resolve, reject } pair. Both functions act on the same promise and share a record of whether either one has already been called.</p><p>We’ll come back to resolving with another promise. First, let’s see what happens when the outcome is already known.</p><h3>Settling the promise</h3><p>We use #fulfill for a fulfillment value and #reject for a rejection reason. Both call the same #settle method:</p><pre>#settle(status: PromiseStatus, result: unknown, reactions: Reaction[]) {<br>    this.#status = status;<br>    this.#result = result;<br>    this.#fulfillReactions = [];<br>    this.#rejectReactions = [];<br>    reactions.forEach((reaction) =&gt; queueMicrotask(() =&gt; reaction(result)));<br>}<br>#fulfill(value: unknown) {<br>    this.#settle(FULFILLED, value, this.#fulfillReactions);<br>}<br>#reject(reason: unknown) {<br>    this.#settle(REJECTED, reason, this.#rejectReactions);<br>}</pre><p>FULFILLED and REJECTED hold the strings &quot;fulfilled&quot; and &quot;rejected&quot;. The method stores the state and result, resets both arrays, and queues the relevant reactions. The array passed into #settle is still available through the reactions parameter because we assigned new arrays to the fields. We didn&#39;t empty the old array in place.</p><p>ECMAScript defines separate operations, <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-fulfillpromise">FulfillPromise</a> and <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-rejectpromise">RejectPromise</a>. Each stores the result, updates the state, and triggers the corresponding reactions. Our method shares those steps between the two paths. Both paths leave the promise settled.</p><h3>Why queueMicrotask?</h3><p>Remember those interview questions about the event loop? We’ve made it to microtasks. If we called a then handler directly from #settle, it could run before the current synchronous code finished. We use queueMicrotask to queue each reaction for later.</p><p>Here’s how the example from the beginning plays out in a browser:</p><pre>Current code:  &quot;before&quot; → executor → resolve(42) → &quot;after&quot;<br>Microtasks:    then handler → 42<br>Browser:       updates rendering if needed</pre><p>In this example, the browser drains the microtask queue after the current task and before it may update rendering. That includes microtasks queued while other microtasks are running. This is a simplified timeline. Rendering doesn’t necessarily happen after every task. ECMAScript defines Promise jobs, and the browser host queues those jobs as microtasks. The browser event loop is described in the <a href="https://html.spec.whatwg.org/multipage/webappapis.html#event-loops">HTML Standard</a>.</p><h3>Attaching handlers with then</h3><p>Now we need to give those reaction arrays something to hold. then also returns a <strong>new</strong> promise, which is what lets us chain calls:</p><pre>new PromiseCore&lt;number&gt;((resolve) =&gt; resolve(2))<br>    .then((value) =&gt; value * 2)<br>    .then((value) =&gt; console.log(value)); // 4</pre><p>The first handler returns 4, so the next promise is fulfilled with that value. If the handler throws, the next promise is rejected.</p><p>To make chaining work, we’ll save the functions that can resolve or reject the next promise:</p><pre>let resolveNext!: Resolve&lt;R1 | R2&gt;;<br>let rejectNext!: Reject;<br>const next = new PromiseCore&lt;R1 | R2&gt;((resolve, reject) =&gt; {<br>    resolveNext = resolve;<br>    rejectNext = reject;<br>});</pre><p>The executor runs synchronously, so the functions are assigned before we use them. The exclamation marks are definite assignment assertions. They tell TypeScript that the variables will be assigned before they’re read. For now, next is pending.</p><p>What we pass to those functions depends on which handler runs and whether one was provided:</p><pre>const runFulfilled: Reaction = (value) =&gt; {<br>    if (typeof onFulfilled !== &quot;function&quot;) {<br>        resolveNext(value as R1);<br>        return;<br>    }<br>    try {<br>        resolveNext(onFulfilled(value as T));<br>    } catch (error) {<br>        rejectNext(error);<br>    }<br>};<br><br>const runRejected: Reaction = (reason) =&gt; {<br>    if (typeof onRejected !== &quot;function&quot;) {<br>        rejectNext(reason);<br>        return;<br>    }<br>    try {<br>        resolveNext(onRejected(reason));<br>    } catch (error) {<br>        rejectNext(error);<br>    }<br>};</pre><p>If there’s no fulfillment handler, the value passes through. If there’s no rejection handler, the reason passes through as a rejection. If onRejected returns a value, we call resolveNext, so the chain can recover from the rejection. An exception thrown by either handler rejects next.</p><p>Now we can decide when to run the reactions:</p><pre>if (this.#status === PENDING) {<br>    this.#fulfillReactions.push(runFulfilled);<br>    this.#rejectReactions.push(runRejected);<br>} else {<br>    const reaction = this.#status === FULFILLED ? runFulfilled : runRejected;<br>    const result = this.#result;<br>    queueMicrotask(() =&gt; reaction(result));<br>}<br><br>return next;</pre><p>If the original promise is still pending, we store both reactions so #settle can use the right one later. If it&#39;s already settled, we queue the appropriate reaction immediately. Either way, the handler runs after the current synchronous code.</p><p>In the full signature, then&lt;R1 = T, R2 = never&gt;, R1 describes the fulfillment handler&#39;s result type and R2 describes the rejection handler&#39;s. The method returns PromiseCore&lt;R1 | R2&gt;. You can find the full method and its type declarations in the <a href="https://github.com/Nodal-dot/toolkit/blob/main/snippets/vanilla/internals/promiseCore/promiseCore.ts">source code</a>.</p><p>That makes catch a one-liner:</p><pre>catch&lt;R = never&gt;(onRejected?: OnRejected&lt;R&gt;): PromiseCore&lt;T | R&gt; {<br>    return this.then(undefined, onRejected);<br>}</pre><p>It attaches a rejection handler through then and returns the resulting promise.</p><h3>Implementing resolve and reject</h3><p>Back to the functions we pass to the executor. Each pair shares an alreadyResolved flag:</p><pre>#createResolvingFunctions(): { resolve: Resolve&lt;unknown&gt;; reject: Reject } {<br>    let alreadyResolved = false;<br>    const resolve: Resolve&lt;unknown&gt; = (resolution) =&gt; {<br>            if (alreadyResolved) return;<br>            alreadyResolved = true;<br>            // Handle resolution here.<br>        };<br>        const reject: Reject = (reason) =&gt; {<br>            if (alreadyResolved) return;<br>            alreadyResolved = true;<br>            this.#reject(reason);<br>        };<br>        return { resolve, reject };<br>}</pre><p>Suppose resolve takes another promise that&#39;s still pending. Our promise stays pending too, but it&#39;s already committed to following the other promise. The flag makes sure that a later call to resolve or reject can&#39;t override that decision. This is how a promise can be <strong>resolved</strong> while it&#39;s still <strong>pending</strong>.</p><p>reject passes the reason straight to #reject. For resolve, we first check what we were given.</p><pre>if (resolution === this) {<br>    this.#reject(new TypeError(&quot;Chaining cycle detected&quot;));<br>    return;<br>}<br>if (!isObject(resolution)) {<br>    this.#fulfill(resolution);<br>    return;<br>}</pre><p>Resolving a promise with itself rejects it with a TypeError. A primitive can be used immediately as the fulfillment value. Our isObject check includes functions because they can have a then property too.</p><p>For an object, we have to read its then property. Even that read can throw, for example if then is a getter:</p><pre>let then: unknown;<br>try {<br>    then = (resolution as { then?: unknown }).then;<br>} catch (error) {<br>    this.#reject(error);<br>    return;<br>}<br>if (typeof then !== &quot;function&quot;) {<br>    this.#fulfill(resolution);<br>    return;<br>}</pre><p>We read then once. If it isn&#39;t callable, we fulfill the promise with the object itself. If it is callable, we&#39;ve found a thenable and need to adopt its outcome.</p><h3>Adopting a thenable’s outcome</h3><p>We’ve read the thenable’s then property. Now we need to call it so it can report its outcome:</p><pre>const adopt = then;<br>queueMicrotask(() =&gt; {<br>    const { resolve, reject } = this.#createResolvingFunctions();<br>    try {<br>        adopt.call(resolution, resolve, reject);<br>    } catch (error) {<br>        reject(error);<br>    }<br>});</pre><p>We defer the call to then to a microtask. We use call to pass the thenable as this, since its method may need to access its own properties. ECMAScript creates a separate job for this through <a href="https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-newpromiseresolvethenablejob">NewPromiseResolveThenableJob</a>.</p><p>Why create a fresh pair of resolving functions? The original pair’s flag is already set. The fresh pair gives the thenable a way to report its outcome and ignores any subsequent attempts. If its then method calls resolve and then throws, the reject call in the catch block has no effect. If it throws before calling either function, the promise is rejected with the thrown value.</p><p>That’s why our then method passes the handler&#39;s return value to resolveNext. If the handler returns a promise or another thenable, the next promise follows its outcome. If it returns an ordinary value, the next promise is fulfilled with that value.</p><h3>What we built</h3><p>We built a promise core with a synchronous executor, resolving functions that act only on the first call, deferred reactions, chaining, and thenable adoption. PromiseCore is an implementation for learning. The built-in Promise also has features outside its scope, including static methods such as Promise.all and host tracking of unhandled rejections.</p><p>The next time someone asks you “What is a Promise?”, take a moment to think, scratch your head, have a coffee, and look out the window. Then maybe give them the short answer. Otherwise, half an hour later, you may still be explaining what happens when resolve finds a callable then, and your interviewer will have finished their coffee and started looking out the window too.</p><p>Have fun experimenting. May your code run before your coffee goes cold. ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cccf9313b771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop adding console.log everywhere: see values right in your code]]></title>
            <link>https://medium.com/@nodaldot/stop-adding-console-log-everywhere-see-values-right-in-your-code-a7122dc34e1d?source=rss-431fae6dd776------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7122dc34e1d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[NodalDOT]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 09:46:08 GMT</pubDate>
            <atom:updated>2026-11-18T09:46:08.742Z</atom:updated>
            <content:encoded><![CDATA[<h4>How code-trace works: highlighting evaluated expressions and showing their values alongside your code.</h4><figure><img alt="Code-trace showing live expression values next to the code in a shipping cost calculation" src="https://cdn-images-1.medium.com/max/1024/1*oIhQv2dCCLooOXFbGjvnxQ.png" /><figcaption>Change the inputs and watch code-trace update the values next to each expression in the shipping cost example.</figcaption></figure><p><em>Originally published on my blog. </em><a href="https://nodaldot.space/en/posts/3"><em>Read the full article for free</em></a><em>.</em></p><p>I wanted to see which expressions were evaluated and what values they produced, right in the code. Without adding console.log everywhere, only to remove all those calls later.</p><p>That’s how code-trace started. Run a function, and values appear alongside the code. Change the arguments and run it again: you get new values and highlights showing which parts of the code were reached.</p><p>Let’s see how it works. We’ll start with a three-line function.</p><h3>Just wrap the value</h3><p>Suppose we have this age check:</p><pre>function check(age) {<br>    if (age &gt;= 18) return &quot;You&#39;re in&quot;;<br>    return &quot;Not old enough yet&quot;;<br>}</pre><p>Let’s wrap age &gt;= 18 in trace: it logs the value and returns it unchanged. The check still works as before.</p><pre>function trace(label, value) {<br>    console.log(label, value);<br>    return value;<br>}<br>function check(age) {<br>    if (trace(&quot;age &gt;= 18&quot;, age &gt;= 18)) return &quot;You&#39;re in&quot;;<br>    return &quot;Not old enough yet&quot;;<br>}<br>check(16);<br>// age &gt;= 18 false</pre><p>The trick is return value. If we just returned true, we&#39;d stop observing the program and start helping underage guests get in. 🙂</p><p>Now let’s add another condition:</p><pre>function check(age, hasInvite) {<br>    if (trace(&quot;age &gt;= 18&quot;, age &gt;= 18)) {<br>        if (trace(&quot;hasInvite&quot;, hasInvite)) {<br>            return trace(&quot;result&quot;, &quot;You&#39;re in&quot;);<br>        }<br>        return trace(&quot;result&quot;, &quot;Invitation required&quot;);<br>    }<br>    return trace(&quot;result&quot;, &quot;Not old enough yet&quot;);<br>}<br><br>check(20, false);<br>// age &gt;= 18 true<br>// hasInvite false<br>// result Invitation required</pre><p>It works. But half the function is now debugging code. Add more nested conditions, and we’ll need more wrappers. Then we’ll have to remove them all.</p><p>I’d rather leave the source alone and add these calls automatically. First, though, we need to <strong>find the expressions in the code</strong> that we want to wrap.</p><h3>Could we just find the parentheses after if?</h3><p>For if (age &gt;= 18), that sounds reasonable. Find if, take the text between the parentheses, and insert trace.</p><p>Then we come across this:</p><pre>if (users.some((user) =&gt; user.roles.includes(&quot;admin&quot;))) {<br>    openPanel();<br>}</pre><p>Now we have several pairs of parentheses. Add strings, comments, and template literals, and our text search gradually turns into a JavaScript parser of its own. All we wanted was to see what a function returned.</p><p>And if isn&#39;t the only place we&#39;re interested in. We also want to observe expressions after return, on the right-hand side of variable declarations, in loop conditions, and in ternary expressions.</p><p>It’s important to distinguish return from the expression after it. In return result, we wrap only result, giving us return trace(&quot;result&quot;, result). The return statement stays in place and returns the value it receives.</p><p>For a closer look at the difference between statements and expressions, Josh W. Comeau has a <a href="https://www.joshwcomeau.com/javascript/statements-vs-expressions/">clear explanation with examples</a>.</p><h3>Reading code as a tree</h3><p>Instead of searching through text, we can use a parser to read the code. It builds an <strong>AST: an abstract syntax tree</strong>. The AST consists of nested objects describing parts of the code: conditions, function calls, and strings. An if statement and the string &quot;if&quot; are now different kinds of nodes, so we won&#39;t mistake one for the other.</p><p>If you’re new to ASTs, Bohdan Liashenko has a <a href="https://itnext.io/ast-for-javascript-developers-3e79aeb08343">detailed introduction with JavaScript examples</a>. He explains how text becomes a tree and how Babel, refactoring tools, and Prettier use it.</p><p>Let’s take a small example:</p><pre>if (age &gt;= 18) allow();</pre><p>Here’s a <strong>simplified AST diagram for this example</strong>, using the format our parser returns. We’ll show only the fields and nodes we need:</p><pre>Program<br>└─ body[0]: IfStatement<br>   ├─ test: BinaryExpression (operator: &gt;=)<br>   │  ├─ left: Identifier (name: age)<br>   │  └─ right: Literal (value: 18)<br>   └─ consequent: ExpressionStatement<br>      └─ expression: CallExpression<br>         ├─ callee: Identifier (name: allow)<br>         └─ arguments: []</pre><p>No more guessing which parentheses belong together. In this tree, IfStatement.test is the expression age &gt;= 18, and consequent is the statement that runs if the condition is truthy.</p><p>For return result, the parser creates a ReturnStatement node with the expression result in its argument field. For a bare return;, that field is null.</p><p>Our parser also gives nodes start and end offsets in the source. For example, the condition here has start: 4 and end: 13, so source.slice(4, 13) returns age &gt;= 18. Field names and position formats vary between parsers. From here on, we&#39;ll use Oxc&#39;s format.</p><p>Tools for <strong>code analysis and transformation</strong> use these trees. A <strong>linter</strong> can look for suspicious code, a <strong>formatter</strong> can print it according to its formatting rules, and we can <strong>find places to observe values</strong>.</p><h3>Which parser should we use?</h3><p>We need a parser that can read our code and tell us where each expression starts and ends.</p><p>Here are a few familiar options:</p><ul><li><a href="https://babeljs.io/docs/babel-parser">Babel parser</a>. You’re already using Babel. Its default AST differs from ESTree. The estree plugin provides compatibility.</li><li><a href="https://github.com/acornjs/acorn">Acorn</a>. You need to parse standard JavaScript. JSX and TypeScript require additional plugins.</li><li><a href="https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API">TypeScript Compiler API</a>. You need type information as well as syntax nodes. It has its own AST format; type information is accessed separately through the TypeChecker.</li><li><a href="https://oxc.rs/docs/guide/usage/parser.html">Oxc</a>. You need to parse JavaScript, TypeScript, and JSX. Parsing TypeScript does not, by itself, mean checking its types.</li></ul><p>ESTree is a widely used specification for JavaScript ASTs. That doesn’t mean every parser returns the same tree. Even similar nodes can have different fields. I wouldn’t move traversal code between libraries without checking those differences first.</p><p>I used what was already available through Vite. I don’t feel like writing my own parser just to show a few values next to some code. There are other ways to ruin a weekend. 😞</p><h3>Finding places for the wrappers</h3><p>First, let’s mark the expressions whose values we want to see. We’ll call each of these locations an <strong>observation point</strong>, or a probe in the code. For now, all we need is its range in the source:</p><pre>type Probe = { start: number; end: number };</pre><p>We don’t have any values or hit counts yet. We’ve only parsed the code; it hasn’t run.</p><p>Here’s a shorter version of the code that collects these probes, using the same imports as the project:</p><pre>import { parseSync, Visitor } from &quot;vite&quot;;<br><br>const source = &quot;if (age &gt;= 18) allow();&quot;;<br>const { program, errors } = parseSync(&quot;example.js&quot;, source, {<br>    preserveParens: false,<br>});<br><br>if (errors.length) throw new Error(&quot;Could not parse the code&quot;);<br><br>const probes: { start: number; end: number }[] = [];<br><br>new Visitor({<br>    IfStatement(node) {<br>        probes.push({ start: node.test.start, end: node.test.end });<br>    },<br>    ReturnStatement(node) {<br>        if (node.argument) {<br>            probes.push({ start: node.argument.start, end: node.argument.end });<br>        }<br>    },<br>}).visit(program);<br><br>console.log(probes);<br>// [{ start: 4, end: 13 }]<br>console.log(source.slice(probes[0].start, probes[0].end));<br>// age &gt;= 18</pre><p>Visitor walks the tree, including nested constructs. We specify what to do when it encounters a node type we&#39;re interested in. It finds a nested if just as it finds the outer one.</p><p>A bare return; has no argument, which is why we check for one. There&#39;s nothing to wrap there.</p><p>The full implementation collects more probes: conditions in while, do...while, and for loops; the expression being matched in a switch; the argument of throw; the condition in a ternary expression; the right-hand side of a variable declaration; and the expression bodies of arrow functions. It also handles standalone expressions such as save();.</p><p>Directives such as &quot;use strict&quot; are skipped. We also skip function and class expressions on the right-hand side of variable declarations. We can&#39;t wrap everything indiscriminately: in some cases, doing so would change how the code behaves.</p><h3>Adding wrappers to the source</h3><p>For a single condition, the transformation looks like this:</p><pre>// Before<br>if (age &gt;= 18) allow();<br><br>// After: showing only the wrapper around the condition<br>if (__trace$(0, age &gt;= 18)) allow();</pre><p>0 is the probe ID: its index in the array.</p><p>Why do we need extra parentheses around the expression? Suppose the code contains return (save(), 42): it calls save() first, then returns 42. Here, the comma operator evaluates the expressions from left to right and produces the value of the last one.</p><p>We need to wrap the comma expression in parentheses so it stays a single argument.</p><pre>// Without parentheses: three arguments instead of two<br>return __trace$(0, save(), 42);<br><br>// With parentheses: the second argument is the value of the whole expression, 42<br>return __trace$(0, (save(), 42));</pre><p>In the first case, the wrapper receives the return value of save() as its value argument, rather than 42. That&#39;s why we always add parentheses around the expression we&#39;re wrapping.</p><p>But inserting text near the beginning of the source shifts every offset after it. So the project collects all the insertions first, then builds the result in a single pass from pieces of the <strong>original</strong> source string. We don’t modify that string during the pass.</p><p>Each probe needs two insertions:</p><pre>{ at: start, text: `__trace$(${id}, (` }<br>{ at: end, text: &quot;))&quot; }</pre><p>Nesting needs some care, too. For example, the right-hand side of a variable declaration and the condition in a ternary expression can start at the same offset:</p><pre>const label = age &gt;= 18 ? &quot;Allowed&quot; : &quot;Not allowed&quot;;</pre><p>Here, we want to see both the condition’s result and the selected string:</p><pre>const label = __trace$(0, __trace$(1, age &gt;= 18) ? &quot;Allowed&quot; : &quot;Not allowed&quot;);</pre><p>When two opening insertions share the same offset, the outer one must come first: <strong>the one wrapping the longer expression</strong>. At the boundary between adjacent expressions, we close the previous wrapper before opening the next one. The sorting logic in wrap-probe.ts handles these cases.</p><p>We could modify the tree itself and print the entire file again. I stuck to text insertions: they’re enough for this task, and they preserve the original formatting.</p><h3>Where the values come from</h3><p>The parser sees age &gt;= 18, but it doesn&#39;t know what value age will have or what the comparison will produce. <strong>To find out, we need to run the code.</strong> That&#39;s why we add wrappers: when execution reaches an expression, the wrapper receives its result, saves it for display, and returns it unchanged.</p><p>Here’s a simplified runtime:</p><pre>const values = new Map&lt;number, unknown&gt;();<br>const hits = new Map&lt;number, number&gt;();<br><br>function __trace$&lt;T&gt;(id: number, value: T): T {<br>    values.set(id, value);<br>    hits.set(id, (hits.get(id) ?? 0) + 1);<br>    return value;<br>}<br><br>__trace$(0, 20 &gt;= 18);<br>__trace$(0, 16 &gt;= 18);<br><br>console.log(values.get(0)); // false<br>console.log(hits.get(0)); // 2</pre><p>The expression is evaluated once, before its result is passed to the function. That matters for calls with side effects:</p><pre>const item = __trace$(0, queue.shift());</pre><p>If we called queue.shift() once for logging and again for the result, we&#39;d unexpectedly remove two items from the queue. That would be quite the debugging tool.</p><p>The actual runtime stores <strong>a short description of each value</strong>. Here’s what ends up in values:</p><pre>import { __trace$, values } from &quot;@toolkit/code-trace/runtime&quot;;<br><br>__trace$(0, [10, 20, 30]);<br>__trace$(1, { name: &quot;Anna&quot;, age: 20 });<br>__trace$(2, function greet() {});<br><br>console.log(values.get(0)); // Array(3)<br>console.log(values.get(1)); // { name, age }<br>console.log(values.get(2)); // ƒ greet</pre><p>This way, even a large array fits into a small label. We don’t copy its contents; we only record a description.</p><p>The run set holds the IDs of probes reached <strong>during the current run</strong>. Let&#39;s start a new run and see what&#39;s left:</p><pre>import { __trace$, values, hits, run, startRun, reset } from &quot;@toolkit/code-trace/runtime&quot;;<br><br>reset();<br><br>__trace$(0, 42);<br><br>console.log([...run]); // [0]<br><br>startRun();<br><br>console.log([...run]); // [] - no probes have been reached in the new run yet<br><br>console.log(values.get(0)); // &quot;42&quot; - the last value is still there<br><br>console.log(hits.get(0)); // 1 - so is the hit count<br><br>reset();<br><br>console.log(values.size, hits.size, run.size); // 0 0 0</pre><p>What if a probe is reached a hundred times in a loop? The stored value and hit count update a hundred times, but <strong>the subscriber receives one notification</strong>:</p><pre>import { __trace$, subscribe } from &quot;@toolkit/code-trace/runtime&quot;;<br><br>let updates = 0;<br><br>const unsubscribe = subscribe(() =&gt; updates++);<br><br>for (let i = 0; i &lt; 100; i++) {<br>    __trace$(0, i);<br>}<br><br>console.log(updates); // 0<br><br>await Promise.resolve(); // let the queued microtask run<br><br>console.log(updates); // 1<br><br>unsubscribe();</pre><p>The runtime uses queueMicrotask to defer the notification. While the synchronous code is running, further hits don&#39;t queue more notifications. Once that code finishes and execution yields to the microtask queue, the UI receives a single update with all the accumulated changes.</p><h3>Putting it together with Vite</h3><p>I have a <a href="https://github.com/Nodal-dot/toolkit">small project</a> where I try out ideas and collect components I like. That’s where I built code-trace and added a playground to test it with live examples.</p><p>The playground runs on Vite, so a plugin is a convenient way to bring everything together: find the expressions, add the wrappers, and show values alongside the source.</p><p>Here’s how to register the plugin:</p><pre>import { codeTrace } from &quot;@toolkit/code-trace/vite&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br><br>export default defineConfig({<br>    plugins: [codeTrace()],<br>});</pre><p>The HTML specifies which file to display:</p><pre>&lt;code-trace src=&quot;example.ts&quot;&gt;&lt;/code-trace&gt;<br>&lt;script type=&quot;module&quot; src=&quot;./main.ts&quot;&gt;&lt;/script&gt;</pre><p>The plugin finds these elements and keeps track of their source files. For the UI, it loads the original text through ?raw and the probe offsets through a custom ?probes query. When the application imports the module itself, the transform hook adds the wrappers and the runtime import.</p><p>We display the original source, but run <strong>the version with the added </strong><strong>__trace$ calls</strong>. The loaded text and offsets are passed to the web component, which places small value labels next to the expressions.</p><p>The element doesn’t call the function itself. In the playground, an input event handler does that:</p><pre>import { startRun } from &quot;@toolkit/code-trace/runtime&quot;;<br>import { check } from &quot;./example.ts&quot;;<br><br>const input = document.querySelector(&quot;input&quot;)!;<br>input.addEventListener(&quot;input&quot;, () =&gt; {<br>    startRun();<br>    check(Number(input.value));<br>});</pre><p>Change the number, and check runs, the values update, and lines with reached probes are highlighted. A line&#39;s hit count is the highest hit count among its probes, not their sum: two expressions on one line don&#39;t, by themselves, mean the line ran twice.</p><h3>Why not just use a debugger?</h3><p>Sometimes that’s exactly what you need.</p><p>If I need to pause inside a function and inspect the call stack, closures, or object state, I’d open DevTools. If I only need one value, I’d add a console.log. There&#39;s no need to build a plugin just for that.</p><p>I wanted something visual: run an example and see which expressions were evaluated and what values they produced, right next to the code. No breakpoints to set or logging calls to add by hand. In the playground, all you need to do is change the number in the input.</p><p>Some tools charge for similar features. I wanted to try building my own version and find out how it works.</p><p>Code-trace is useful for a different kind of task: you have a small algorithm in front of you, change its inputs, and immediately see what happened. You might be exploring early returns, explaining a loop, or testing a few branches in a teaching example.</p><p>There are also code coverage tools, which help you find lines and branches your tests didn’t reach. But “did this branch run?” is a different question from “what value did this expression produce?” With code-trace, I wanted to see the values as well as which parts of the code ran.</p><h3>Where the magic stops</h3><p>Code-trace still has a few limitations.</p><p>In a &amp;&amp; b, the right-hand side is evaluated only if the left-hand side is truthy. The wrapper preserves that behavior. If b wasn&#39;t evaluated, we can&#39;t show its result.</p><p>There’s a catch with errors, too. If evaluating an expression throws, __trace$ is never called: the argument is evaluated first. With throw new Error(...), though, we can record a description of the newly created error object before it is thrown.</p><p>Each probe stores <strong>only its latest value</strong>. If a loop runs a hundred times, you won’t be able to inspect all hundred results. There is no value history or chronological call log. And startRun() simply marks the start of a new run. If two asynchronous operations overlap, their results can get mixed together.</p><p>Support for multiple files isn’t quite there yet, either. Probe IDs start at zero in each file, but all their values share the same store. Probe 0 from one file can therefore collide with probe 0 from another. We need to include a file identifier.</p><p>The name __trace$ is currently fixed. If the source already declares a variable with that name, there&#39;s a conflict. No source map is generated yet, either, which makes it harder to map positions in the transformed code back to the original source.</p><p>And one more thing: <strong>returning the same value isn’t always enough</strong>. JavaScript can infer an anonymous function’s name from the variable it’s assigned to. A wrapper can prevent that, so we skip function and class expressions in variable declarations. Each new case needs to be checked separately.</p><p>This is already enough for a small playground. There’s still plenty of work to do before it could be a general-purpose debugger for an entire project.</p><p>What I like most is that you can start with a three-line function. Then you ask, “Could we add these calls automatically?” Suddenly, ASTs no longer feel like something only compiler authors get to use.</p><p>The full implementation is in my <a href="https://github.com/Nodal-dot/toolkit/tree/main/packages/code-trace">toolkit, in the code-trace package</a>. Start with instrument/collect-probes.ts, then look at wrap-probe.ts and runtime/index.ts. The playground contains an example that connects it all to a number input and a code view.</p><p>Good luck with your experiments! May your code work and your coffee stay warm. ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7122dc34e1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>