<?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 Marsha Teo on Medium]]></title>
        <description><![CDATA[Stories by Marsha Teo on Medium]]></description>
        <link>https://medium.com/@marshateo?source=rss-4efda1f7b8d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dTs6X4Yb4i7QwWYD0uLDAQ.jpeg</url>
            <title>Stories by Marsha Teo on Medium</title>
            <link>https://medium.com/@marshateo?source=rss-4efda1f7b8d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:53:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marshateo/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[Where Does “Meaning” Come From in a Transformer?]]></title>
            <link>https://code.likeagirl.io/where-does-meaning-come-from-in-a-transformer-bc957f464957?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc957f464957</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 12:06:01 GMT</pubDate>
            <atom:updated>2026-09-21T12:06:01.372Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How I learned to think about CLS tokens, positional embeddings, queries, keys and values</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XHnNKvXJv-kl3oWHB-G1Q.png" /><figcaption>Meaning emerges from how representations are used within the transformer</figcaption></figure><p>I’ve been learning about Vision Transformers, and it’s been a ride. It’s probably the densest architecture I’ve studied so far, and it seems loaded with components that border on the miraculous.</p><ul><li>There’s the CLS token. We stick it in front of the patch embeddings, and somehow it comes to represent the image for classification. Very convenient.</li><li>Then there are queries, keys and values. Every token produces all three, and together they determine which other tokens to pay attention to and what information to retrieve from them.</li><li>And before any of that, we add positional embeddings to the patch embeddings, and now the model can account for where patches came from in the original image. Great!</li></ul><p>The explanations always started with what these components represented. CLS represented the image. Queries looked for relevant information, keys identified what was available, and values carried the information itself. Positional embeddings represented where each patch came from.</p><p>I understood the roles each component was supposed to play. But where did all this meaning come from?</p><ul><li>What made the CLS token a representation of the image in the first place?</li><li>What made one projection a query and another a key, when they were constructed in almost exactly the same way</li><li>Where was “position” actually encoded in a positional embedding?</li></ul><p>The answer seemed to be: training. Backpropagation.</p><p>Okay. Backpropagation is amazing, but it isn’t magic. It still didn’t make sense to me why these parameters would represent the things they said they would.</p><p>Then something embarrassingly simple clicked: I had the explanatory direction backwards.</p><ul><li>A CLS token isn’t first an image representation that we then decide to use for classification. We decide to use its final state for classification, and that creates pressure for it to become useful for classification.</li><li>A query isn’t first imbued with some property of “query-ness” and then placed into the attention equation. We put the output of one learned projection in the query position of that equation, and training specializes that projection for the role we’ve given it.</li><li>And a learned positional embedding doesn’t begin with “position” encoded somewhere inside its random numbers. We consistently use the parameter at a particular position, and training shapes its values according to what is useful when it is used there.</li></ul><p>The names describe the jobs we’ve given these parameters, not something inherent in their initial values.</p><h3><strong>What Makes CLS an Image Representation?</strong></h3><p>The name makes this question surprisingly easy to overlook. It’s called the <em>classification token</em>. Diagrams label it [CLS]. In a Vision Transformer used for image classification, its final CLS state is fed to the classifier and explanations tell us that it ‘represents the image’. After seeing enough diagrams, I started to feel as though being an image-level representation is somehow a property of the token itself.</p><p>But CLS doesn’t start that way. In the beginning of time, it is initialised randomly. There’s nothing inherently image-like about it. how does this arbitrary vector end up representing the image?</p><p>The answer is obvious once stated, but it changed how I think about these architectures: We use its final state for classification, so training has reason to make that state informative about the image.</p><p>I had been reasoning in the direction of the forward pass: CLS gathers information from the image, becomes an image representation, and then we use that representation for classification.</p><p>But I found it more useful to reason backward from the loss. At the end of a Vision Transformer used for classification, we do roughly this:</p><p><strong>[CLS] representation → classifier → prediction → loss</strong></p><p>The classifier only gets the final CLS representation. That means if the CLS representation is useless for say, distinguishing a dog from a cat, the network has a problem. Then the familiar sequence follows: A poor prediction produces a high loss; backpropagation follows; parameters involved get changed. Over many training examples, this puts pressure on the network to make the final CLS representation useful for the classification task.</p><p>And “useful” doesn’t have to be a rich, general-purpose representation of ‘the image.’ It doesn’t necessarily mean that CLS develops a neat, human-readable summary of the image — two ears, four legs, big eyes, and so on. It simply encodes features that help the classifier distinguish the classes it is being trained on. As classification improves, we describe CLS as an “image representation,” but more precisely, it is a representation shaped around whatever information about the image is useful for classification.</p><p>So it isn’t that:</p><p><strong>CLS represents the image → therefore we classify using CLS</strong></p><p>It is closer to:</p><p><strong>We classify using CLS → training makes CLS useful for classification</strong></p><p>But making classification depend on CLS isn’t enough. Information about the image also needs a way to reach it. By letting CLS participate in self-attention alongside the patch tokens, the architecture gives it a pathway to gather and consolidate information from them.</p><p>The architecture has not told CLS what an image is. Instead, it has done two simpler things: made successful classification depend on the final state of CLS, and given CLS access to information that could help it succeed. Training does the rest: the loss provides the pressure; backpropagation communicates that pressure through the network; the parameters controlling how CLS interacts with the patches are gradually adjusted. The architecture assigns the role. Training learns the content.</p><h3><strong>Where Is the Position in a Positional Embedding?</strong></h3><p>Once I noticed this, I realized I had been making essentially the same mistake with learned positional embeddings. When I first came across them, I kept wondering where the position was actually encoded. What about the embedding for position 1 made it mean ‘position 1’?</p><p>Then came the explanation that they were initialised randomly, just like any other learned parameter. At initialisation, those numbers contain nothing inherently position-related. So what eventually makes one of those arbitrary vectors the embedding for position 1?</p><p>Nothing in the vector itself initially says ‘position 1.’ It becomes the position-1 embedding because we consistently add that same learned vector to the token occupying position 1. That repeated association gives the parameter its role. Training then shapes its values according to what is useful for a parameter that is always used there. The parameter doesn’t eventually come to mean ‘position 1’. Rather, its learned effects become useful given that it is always injected at position 1.</p><p>The architecture created the association; training shaped the values around it:</p><ul><li><strong>Architecture</strong>: This is the parameter that will always be used at position 1.</li><li><strong>Training</strong>: Given that role, what values would actually be useful?</li></ul><h3><strong>What Makes a Query a Query?</strong></h3><p>The equations for queries, keys and values look remarkably similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*ajWI0bht_xhHBRhJQUIFeA.png" /></figure><p>We take the same token representations <em>X</em> and pass them through three learned linear projections (<em>W_Q</em>, <em>W_K</em>, and <em>W_V</em>). When I first encountered this, I kept wondering: what actually makes one of these a query and another a key? How does <em>W_Q</em> know that it is supposed to learn “queries”, while <em>W_K</em> learns “keys”?</p><p>Looking only at these projection equations didn’t answer the question. They’re just different learnable matrices, initialized independently and trained through gradient descent.</p><p>The difference only becomes visible when we look at what happens to their outputs next. You can’t tell why <em>Q</em> is a query by looking at the equation above; you have to follow <em>Q</em> in the attention computation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*XxpX_PUXf81JMy44YqnA7Q.png" /></figure><p>Although <em>Q</em>, <em>K</em>, and <em>V</em> are produced in essentially the same way, their outputs occupy different places in the attention computation. <em>Q</em> and <em>K</em> jointly determine the attention scores, but occupy different sides of the relationship: a token’s query is compared against the keys of the tokens it might attend to. <em>V</em> has a more obviously different role: once the attention weights have been calculated, those weights are used to combine the value vectors.</p><p>That’s what makes <em>Q</em> the query here: not anything inherent in the numbers produced by <em>W_Q</em>, but the fact that we consistently use its output in the query position of this computation.</p><p>As a result, changing each projection can have different consequences:</p><p>- If changing <em>W_Q</em> would improve which other tokens a token attends to, training can adjust <em>W_Q</em>.</p><p>- If changing <em>W_K</em> would improve which tokens receive attention from other tokens, training can adjust <em>W_K</em>.</p><p>- If changing <em>W_V</em> would improve the information that gets passed along under those attention weights, training can adjust <em>W_V</em>.</p><p>The loss reflects those different consequences; backpropagation computes the corresponding gradients; the optimizer adjusts the parameters. Over training, the three matrices specialize.</p><p>I had been thinking:</p><p><strong>This is a query → therefore we use it as a query</strong></p><p>But the more useful explanatory direction is:</p><p><strong>We use this projection as the query → training makes it useful in that role</strong></p><p>The same applies to keys and values.</p><h3><strong>Maybe the Names Are Part of the Problem</strong></h3><p>I think some of my confusion came from the names being too good: <em>Classification token</em>, <em>Positional embedding</em>, <em>Query</em>, <em>Key</em>, and <em>Value</em>. In the simpler models I’d studied, I hadn’t encountered names that seemed to carry quite so much meaning.</p><p>These names are useful shorthand, but they can make it sound as though the concept described by the name is somehow an inherent property of the numbers:</p><ul><li>A CLS vector sounds like a vector that intrinsically contains classification-related information.</li><li>A positional embedding sounds like a vector that intrinsically contains a position.</li><li>A query sounds like something that intrinsically asks a question.</li></ul><p>The names describe the roles we have arranged for these components to play, not some intrinsic meaning carried by the numbers themselves. The distinction feels obvious once stated. Unfortunately, it wasn’t obvious to me while learning the architecture.</p><h3><strong>How This Changed the Way I Learn Architectures</strong></h3><p>I also realized that part of my difficulty came from how I respond when I don’t understand something. My instinct is to stop there and keep digging until the confusion is resolved. If I’ve just been introduced to a positional embedding and I don’t understand where the ‘position’ comes from, moving on feels like building on top of something I don’t understand.</p><p>But sometimes I had been trying to answer questions before I’d even seen the part of the architecture that made them answerable. You can’t fully understand why <em>Q</em> is a query from <em>Q=XW_Q</em> alone; you have to follow <em>Q</em> into the attention computation. Sometimes understanding an earlier component requires seeing more of the computation and how it connects to the loss, not staring harder at the component itself.</p><p>So when I come across a new learned component in an architecture, my first question is no longer just, ‘What does this represent?’ A better first question is: ‘What is this used for?’. Of course, that is now followed by:</p><ul><li>Where does it enter the computation?</li><li>What can influence it?</li><li>What can it influence?</li><li>Where does its output eventually go?</li><li>Which loss depends on that output?</li><li>What information would make it useful for minimizing that loss?</li><li>Does the architecture provide a pathway for that information to reach it?</li></ul><p>So instead of accepting that ‘CLS represents the image’ as the explanation, I now ask “What about this architecture and objective allows and encourages a useful image representation to emerge at CLS?”</p><p>None of this is a new result about Transformers. It’s closer to a correction in how I had been thinking about them. I had been looking for meaning inside the components themselves, when I should also have been looking at the larger system around them: where the architecture puts them, what information can reach them, what they can affect, and what the objective rewards.</p><p>If you’ve ever looked at a Transformer diagram and had the uncomfortable feeling that terms like <em>CLS token</em> or <em>positional embedding</em> explained what something was doing without quite explaining why those particular numbers should ever come to mean that, this might be the missing distinction:</p><ul><li>The name describes the role we gave it.</li><li>The architecture determines how it can participate.</li><li>The objective gives it something to become useful for.</li><li>Training determines what it actually learns.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc957f464957" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/where-does-meaning-come-from-in-a-transformer-bc957f464957">Where Does “Meaning” Come From in a Transformer?</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning neural networks through mental models]]></title>
            <link>https://code.likeagirl.io/learning-neural-networks-through-mental-models-987640973005?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/987640973005</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 17:11:07 GMT</pubDate>
            <atom:updated>2026-09-10T17:11:07.428Z</atom:updated>
            <content:encoded><![CDATA[<h4>How ideas like function approximation, representation learning, optimisation and computational graphs finally made deep learning feel coherent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j36EWxe2KHTpApsm4vj6KA.png" /></figure><p>For a while, I understood neural networks mostly mechanically. Data entered the network, passed through layers, and eventually produced a prediction. Loss was calculated, gradients computed and weights updated. I could follow the sequence but the pieces still felt strangely arbitrary. Why this structure? Why did stacking layers make a network so powerful? Why were activation functions so important? I understood much of what the network was doing, step by step, without feeling like I understood the network as a whole.</p><p>Then I watched <a href="https://www.youtube.com/watch?v=CqOfi41LfDw&amp;list=PLblh5JKOoLUIxGDQs4LFFD--41Vzf-ME1&amp;index=2">Josh Starmer’s StatQuest video</a> on the key ideas underlying neural networks. He presented neural networks as systems that sculpt functions. Instead of following data through layers, I could zoom out and picture what those transformations were collectively constructing. That shift helped immediately.</p><p>Then I got greedy and started looking for other ways to think about neural networks. By the time I was done, I realised that different mental models made different questions easier to answer. Some let me zoom out and collapse the network into one idea. Others did the opposite, breaking it into smaller transformations or computations. Some connected neural networks to ideas I already understood; others made me reinterpret things I thought I understood already. Together, they made neural networks feel much less mysterious. Learning to switch between these mental models was the breakthrough I needed.</p><h3>Neural networks as stacks of transformations</h3><p>The mechanical understanding I started with was essentially viewing neural networks as a stack of transformations.</p><p>Each layer progressively transforms the data before passing it on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*tMq5oIUpkm0ma9o2BpNZBQ.png" /></figure><p>where</p><ul><li><em>x </em>is the input</li><li><em>h</em>’s are intermediate hidden representations, and</li><li><em>y</em> is the final output.</li></ul><p>This was probably my default mental model before I knew to call it one. It made the forward pass easy to follow: the input is transformed step by step until the network produces an output.</p><p>This perspective helps explain why neural networks have depth at all. Each layer can transform the output of the previous layer, allowing the network to build increasingly complex computations. Earlier layers produce simpler transformations that later layers can refine further.</p><p>At the same time, this perspective kept my attention on the individual steps. I didn’t have a clear picture of what all those transformations were collectively doing. I needed to zoom out.</p><h3>Neural networks as function approximators</h3><p>Function approximation gave me that zoomed-out view.</p><p>I was already comfortable thinking about models like linear and logistic regression as functions. Given some inputs, these models learn a mapping that produces an output. A neural network can be understood in exactly the same way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-E6h3IDDgaOLzYW9lU4Cg.png" /></figure><p>This stripped away much of the apparent mystery surrounding neural networks. Underneath all that machinery, the network was still doing something familiar: learning a function that maps inputs to outputs, just like the other models I already understood. The difference was that neural networks could learn far more flexible and expressive functions.</p><p>But how do these complex functions emerge from simple neurons?</p><h3>Neural networks as function sculptors</h3><p>I already understood abstractly that stacking layers with nonlinear activation functions allowed neural networks to model increasingly complex relationships. But I couldn’t visualise it.</p><p>In Josh Starmer’s <a href="https://www.youtube.com/watch?v=CqOfi41LfDw&amp;list=PLblh5JKOoLUIxGDQs4LFFD--41Vzf-ME1&amp;index=2">explanation</a>, each neuron works with a given activation function. The weights and biases slice, flip and stretch that same activation function into new shapes. As a result, each neuron applies a small nonlinear transformation to its input. These small transformations and shapes are stitched together across layers to create yet new shapes. A complex decision boundary emerges from many local transformations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*bJl0MzSllsZZ1L1Gr1mxpQ.png" /><figcaption>Rather than learning one giant function directly, neural networks build complex behaviour by combining many smaller nonlinear transformations.</figcaption></figure><p>With Softplus, a neuron can contribute a smooth bend into the function surface. With ReLU, neurons contribute piecewise linear changes. Deep networks combine huge numbers of these simple transformations, progressively sculpting a much more complex function.</p><p>Don’t take my word for it. Watch the video. His animations (and the noises he makes while calculating) make it worth your time.</p><p>What clicked for me was that the network didn’t need any individual neuron to represent a complicated function. Each neuron could contribute something simple. Complexity emerged from composing and combining many of those simple transformations.</p><p>Function approximation had helped me zoom out and see the network as one flexible function. Function sculpting let me zoom in just enough to see how that flexibility could be constructed.</p><h3>Neural networks as representation learners</h3><p>One thing that distinguishes neural networks from many of the models I was used to working with is that they can also learn how to represent the input itself.</p><p>In my previous experience with econometrics and causal inference, deciding how to represent a problem happened largely before fitting the model. I thought carefully about which variables to include, what they measured, and how they should be transformed. The model then learned from the representation I had given it.</p><p>With neural networks, deciding how to represent the problem doesn’t happen entirely before training. The network also learns useful ways of representing the data. The hidden states in the stack of transformations aren’t just intermediate <em>values</em> but intermediate <em>representations</em> shaped during training to become useful for the task. This is why neural networks are often described as systems for representation learning.</p><p>This applies even to relatively simple neural networks. For example, a churn model might learn hidden behavioural patterns that help distinguish customers with different risks of leaving. In a larger language model, the learned representations can encode complex semantic relationships. The scale and complexity differ but both are forms of representation learning.</p><p>I had been thinking of learning primarily as learning a mapping from my representation of the problem to the target. Representation learning made me realise that the representation itself could be part of what was learned.</p><h3>Neural networks as optimisation systems</h3><p>One thing that puzzled me when learning about neural networks was the amount of attention given to activation functions. I understood that without them, stacking linear layers still collapses into a linear transformation. But why did the choice of activation function matter?</p><p>I initially thought about activation functions through the function-sculpting perspective. Different activation functions give the network different shapes to work with, so I assumed that choosing between sigmoid, tanh or ReLU was primarily about the kinds of functions the network could construct.</p><p>The optimisation perspective gave me a different answer.</p><p>Unlike simpler models such as linear regression, neural networks generally do not have neat closed-form solutions for their parameters. These parameters are learned iteratively through optimisation. At first glance, optimisation can seem like a secondary implementation detail — merely the mechanism through which weights get updated during training.</p><p>But it isn’t enough for a neural network to be capable of representing a useful function; optimisation has to find the parameters that produce one. Neural networks were already highly expressive decades ago. The challenge was whether optimisation could actually find a useful solution. Gradient-based optimisation struggled to reliably train deep networks. Much of the progress in deep learning has involved making highly expressive neural networks easier to train.</p><p>Many neural network design choices are intended to solve optimisation problems. Sigmoid activation functions can saturate, while ReLU often allows gradients to propagate more effectively. Weight initialisation affects whether signals and gradients remain stable across many layers. Learning rates and optimisers determine how we move through the loss landscape.</p><p>This perspective also changed how I thought about architecture. From my original stack-of-transformations perspective, residual connections seemed strange. If each layer was supposed to progressively transform the representation, why let an earlier representation bypass a block and add it back later?</p><p>From an optimisation perspective, the question changes. Residual connections provide identity paths through deep networks, helping information and gradients flow and allowing blocks to learn changes to an existing representation. What had looked awkward from one mental model made much more sense from another.</p><p>This perspective helped explain why so much of deep learning is about more than designing expressive architectures. It is also about making those architectures trainable.</p><h3>Neural networks as computational graphs</h3><p>The optimisation perspective explains why gradients matter. But how are the gradients computed?</p><p>Function approximation had taught me to think of a neural network as one enormous function. But trying to imagine its derivatives gave me a headache. Differentiating an enormous, complicated function with millions of parameters sounded overwhelming.</p><p>The computational graph perspective reverses that. It breaks this gigantic function back into the small operations that produce it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*Kx6A8cRhG4rBGX_JFYLHRQ.png" /></figure><p>During the forward pass, data moves through the graph step by step: inputs are transformed; activations are computed; predictions are produced; and loss is calculated. Backpropagation then works backwards through this graph to compute the gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*NwYj6YNE-Y1ZPlgFPlubmA.png" /><figcaption>The computational graph perspective decomposes a neural network into smaller differentiable computations. During the forward pass, values flow through the graph to produce a prediction and compute the loss. During the backward pass, gradients flow back through the same graph using the chain rule.</figcaption></figure><p>The key insight is that the gradients aren’t computed as one enormous derivative. Each operation only needs to compute local derivatives with respect to its own inputs. By the magic of chain rule, these local derivatives are stitched together, and gradients are able to propagate backward through the whole network. Backpropagation no longer felt like a memorised algorithm.</p><h3>Conclusion</h3><p>Neural networks became much easier to understand once I stopped searching for a single explanation.</p><p>What I initially thought of as one complicated system could be viewed at very different scales. I could zoom out and view the system as a single function, or zoom in and think about individual transformations and computations. I could think about what representations the network was learning, or switch questions entirely and ask whether optimisation could actually find them.</p><p>What surprised me most was that a mental model that made one question easier could make another harder to reason about</p><ul><li>Thinking of a neural network as one enormous function connected it to more familiar machine learning models but made the idea of differentiating it overwhelming. Instead, breaking that same function into a computational graph made backpropagation much easier to understand.</li><li>Residual connections were initially confusing when I viewed networks as stacks of transformations. However, from an optimisation perspective, their purpose made more sense.</li></ul><p>No single perspective fully explains neural networks. Each lens makes different questions easier to reason about. The real shift was learning which mental model to reach for when something stopped making sense.</p><h3>The mental models: a summary</h3><ol><li><strong>Stack of Transformations</strong><br><em>Why are there multiple layers?</em><br><strong>Main insight</strong>: Layers progressively reshape data into new representations.</li><li><strong>Function Approximation<br></strong><em>What is the network fundamentally doing?<br></em><strong>Main insight</strong>: A neural network is ultimately learning a function from inputs to outputs.</li><li><strong>Function Sculpting</strong><br><em>How do simple neurons create complex functions?</em><br><strong>Main insight</strong>: Complex functions emerge from many simple nonlinear transformations.</li><li><strong>Representation Learning</strong><br><em>What are hidden layers learning?</em><br><strong>Main insight</strong>: Neural networks learn useful internal representations of the input.</li><li><strong>Optimisation System</strong><br><em>Why do so many design choices concern training?</em><br><strong>Main insight</strong>: Expressiveness isn’t enough; optimisation has to find useful parameters.</li><li><strong>Computational Graph</strong><br><em>How are gradients actually computed?</em><br><strong>Main insight</strong>: Derivative calculations can be decomposed into local derivatives stitched together by the chain rule.</li></ol><h3>Resources</h3><ul><li>Josh Starmer (StatQuest): <a href="https://www.youtube.com/watch?v=CqOfi41LfDw"><strong>The Essential Main Ideas of Neural Networks</strong></a></li></ul><p><em>This article grew out of a more detailed exploration of neural network mental models on my </em><a href="https://www.marshateo.com/writing/neural-network-mental-model"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=987640973005" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/learning-neural-networks-through-mental-models-987640973005">Learning neural networks through mental models</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Scheduling Boundaries Behind Responsive UI]]></title>
            <link>https://code.likeagirl.io/the-scheduling-boundaries-behind-responsive-ui-8f5804bcc0e8?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f5804bcc0e8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Fri, 15 May 2026 17:13:40 GMT</pubDate>
            <atom:updated>2026-05-18T05:44:49.360Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>This is the last article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYja4-m8y1YTa0Q07VIs7g.png" /></figure><p>We now know how the event loop and rendering pipeline behave.</p><p>The browser:</p><ul><li>Runs a macrotask to completion.</li><li>Drains all microtasks.</li><li>Executes any scheduled requestAnimationFrame callbacks.</li><li>Drains all microtasks.</li><li>Performs layout and paint to produce the next frame.</li><li>Moves on to the next macrotask.</li></ul><p>Given that environment, how should we write UI code?</p><h3><strong>Long Tasks Block Everything</strong></h3><p>If you want the UI to stay responsive, your tasks must yield quickly.</p><p>Consider this:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  const start = performance.now();<br><br>  while (performance.now() - start &lt; 3000) {<br>    // busy loop for 3 seconds<br>  }<br><br>  console.log(&quot;done&quot;);<br>});</pre><p>Once the button is clicked, the page becomes unresponsive. The click handler is a macrotask and nothing can interrupt it. Everything else has to wait: there is no re-rendering, no new input, no requestAnimationFrame callbacks.</p><p>Long-running tasks monopolize the main thread. While they run, rendering pauses, input waits, animations stall and timers are delayed. Responsive UI depends on cooperation.</p><h3><strong>Microtasks Do Not Yield to Rendering</strong></h3><p>Chaining promises look like a way to break work into pieces:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  Promise.resolve()<br>    .then(() =&gt; heavyWork())<br>    .then(() =&gt; {<br>      status.textContent = &quot;Halfway...&quot;;<br>    })<br>    .then(() =&gt; moreHeavyWork())<br>    .then(() =&gt; {<br>      status.textContent = &quot;Done&quot;;<br>    });<br>});</pre><p>However, each .then() callback becomes a microtask when its associated Promise resolves. Because the browser must drain the entire microtask queue before rendering, chaining Promises does not create render opportunities. As a result, the user sees nothing until “Done” shows up on screen.</p><p>If you want to let the browser render, you must introduce a scheduling boundary:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  Promise.resolve()<br>    .then(() =&gt; heavyWork())<br>    .then(() =&gt; {<br>      status.textContent = &quot;Halfway...&quot;;<br><br>      return new Promise(resolve =&gt; {<br>        // setTimeout used to introduce a scheduling boundary<br>        setTimeout(resolve, 0); <br>      });<br>    })<br>    .then(() =&gt; heavyWork())<br>    .then(() =&gt; {<br>      status.textContent = &quot;Done&quot;;<br>    });<br>});</pre><p>Alternatively, we can consider:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  Promise.resolve()<br>    .then(() =&gt; heavyWork()<br>    .then(() =&gt; {<br>      status.textContent = &quot;Halfway...&quot;;<br><br>      return new Promise(resolve =&gt; {<br>        // requestAnimationFrame used to introduce a scheduling boundary<br>        requestAnimationFrame(resolve); <br>      });<br>    })<br>    .then(() =&gt; heavyWork()<br>    .then(() =&gt; {<br>      status.textContent = &quot;Done&quot;;<br>    });<br>});</pre><p>Both approaches work because a .then() callback is only queued once its associated Promise resolves. By returning a Promise that resolves later, we delay when the next microtask is created. setTimeout yields to the next macrotask, while requestAnimationFrame yields to the next frame.</p><h3><strong>Choosing Between Promises, setTimeout and requestAnimationFrame</strong></h3><p>These mechanisms signal different intentions to the browser. They are not interchangeable.</p><p>Use a Promise when you need to continue work immediately after the current macrotask completes, but before the browser moves on. They are ideal for continuing work that logically depends on previous work. They help to preserve order, transform results and update state after completion. They are not a yielding mechanism.</p><p>Use setTimeout when you need to create a real scheduling gap. They are useful for breaking up long computation, deferring non-critical work and yielding cooperatively. They are general purpose yields.</p><p>Use requestAnimationFrame when you are performing visual updates. It is ideal for animations and layout-sensitive work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*JohS2V4RLObrRChlx2-Fog.png" /><figcaption>Different scheduling APIs solve different coordination problems in the browser event loop</figcaption></figure><h3><strong>Align Visual Updates to Frames</strong></h3><p>Consider this approach:</p><pre>document.addEventListener(&quot;mousemove&quot;, (event) =&gt; {<br>  box.style.left = event.clientX + &quot;px&quot;;<br>});</pre><p>If the mouse fires 200 events per second, this code attempts 200 DOM updates per second. But on most displays, the refresh happens about 60 times per second. Visual work that exceeds that rate is simply wasted.</p><p>Instead, consider:</p><pre>let latestX = 0;<br>let scheduled = false;<br><br>document.addEventListener(&quot;mousemove&quot;, (event) =&gt; {<br>  latestX = event.clientX;<br><br>  if (!scheduled) {<br>    scheduled = true;<br><br>    requestAnimationFrame(() =&gt; {<br>      box.style.left = latestX + &quot;px&quot;;<br>      scheduled = false;<br>    });<br>  }<br>});</pre><p>We use requestAnimationFrame to update at most once per frame, no matter the rate at which input can fire.</p><h3><strong>Respect the Frame Budget</strong></h3><p>requestAnimationFrame guarantees alignment to the frames but it does not guarantee smoothness. On a 60fps display, the browser has roughly 16ms per frames. That 16ms must include all JavaScript and rendering work.</p><p>If the JavaScript executed alone takes longer than that, the browser cannot complete rendering in time:</p><pre>requestAnimationFrame(() =&gt; {<br>  const start = performance.now();<br><br>  while (performance.now() - start &lt; 40) {<br>    // 40ms of work<br>  }<br>});</pre><p>This callback runs before the browser renders but it blocks for 40ms and therefore exceeds the frame budget. Since the browser cannot display partial frames, if the 16ms window is missed, that frame is dropped. Instead of rendering at 60 frames per second, the browser renders less frequently: Animations can appear jerky, motion uneven and interactions delayed.</p><p>So while requestAnimationFrame helped with alignment, we must still finish the frame work within the frame window. Either work fits inside the budget or it is spread across multiple frames. For instance, this could mean animating in steps or deferring non-critical computation.</p><p>Responsive UI requires both correct scheduling and work that fits inside the budget.</p><h3><strong>Guard Against Stale Asynchronous Work</strong></h3><p>Asynchronous code creates delays. During this window, state can change:</p><pre>function loadData() {<br>  fetch(&quot;/data&quot;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      render(data);<br>    });<br>}</pre><p>This looks harmless but imagine the user clicking twice quickly and loadData() is called twice in succession. If the second request finishes first, the first request would render stale data and the UI would then be incorrect.</p><p>One common pattern is to guard against outdated work:</p><pre>let currentRequestId = 0;<br><br>function loadData() {<br>  const id = ++currentRequestId;<br><br>  fetch(&quot;/data&quot;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      if (id !== currentRequestId) return;<br>      render(data);<br>    });<br>}</pre><p>Now each request captures its own response and only the most recent request is allowed to update the UI.</p><h3><strong>Designing With the Browser, Not Against It</strong></h3><p>Responsive UI emerges from working within the browser’s execution model.</p><p>In practice, that often means:</p><ul><li>Keeping tasks short so the browser can continue scheduling</li><li>Remembering that microtasks do not yield to rendering</li><li>Aligning visual updates to frame boundaries</li><li>Ensuring that work fits within the frame budget.</li><li>Verifying that delayed work is still relevant before applying it</li></ul><p>I started this series because I had code that used Promises, setTimeout, and requestAnimationFrame. They all felt “asynchronous” and interchangeable. Turns out they weren’t.</p><p>Good UI code knows which scheduling boundary to use and when.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/event-loop-application"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f5804bcc0e8" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/the-scheduling-boundaries-behind-responsive-ui-8f5804bcc0e8">The Scheduling Boundaries Behind Responsive UI</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[requestAnimationFrame: The Missing Scheduling Layer]]></title>
            <link>https://code.likeagirl.io/requestanimationframe-the-missing-scheduling-layer-66bf15b4e8a0?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/66bf15b4e8a0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Wed, 13 May 2026 20:26:00 GMT</pubDate>
            <atom:updated>2026-05-18T05:43:00.158Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the sixth article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY-yBl2U3-5wOE9SJOZo2g.png" /></figure><p>In the <a href="https://medium.com/code-like-a-girl/rendering-is-a-browser-decision-not-a-javascript-one-7a34f0b292c4">last article</a>, we established that:</p><blockquote>The browser will not render while a macrotask is running nor while microtasks are draining.</blockquote><p>Instead, rendering only happens at stable boundaries. But this creates a new problem: If rendering only happens at specific boundaries, how do we run code <strong>just before</strong> a render? If we want smooth animation, frame-aligned updates, or visual state that reflects the latest input, we need something that runs once per frame right before the browser renders.</p><p>That is the scheduling gap that requestAnimationFrame fills.</p><h3><strong>Running the Experiments</strong></h3><p>These experiments rely on the browser’s rendering behaviour.</p><ol><li>Create a simple HTML file with the following content:</li></ol><pre>&lt;div id=&quot;box&quot;&gt;Initial&lt;/div&gt;</pre><p>2. Open the file in your browser</p><p>3. You can run all code snippets in this series by pasting them into the browser console.</p><p>These examples will not work in Node.js because they depend on the DOM and browser rendering.</p><h3><strong>The Problem Before requestAnimationFrame</strong></h3><p>Developers originally faced a challenge:</p><blockquote>How do I animate smoothly without freezing the UI?</blockquote><p>We may run a naive loop like this where we want update() to advance state and render() to mutate the DOM or canvas:</p><pre>let gameRunning = true;<br><br>function update() {<br>  console.log(&quot;update&quot;);<br>}<br><br>function render() {<br>  console.log(&quot;render&quot;);<br>  const box = document.getElementById(&quot;box&quot;);<br>  box.textContent = `Updated at ${new Date().toLocaleTimeString()}`;<br>}<br><br>while (gameRunning) {<br>  update();<br>  render();<br>}</pre><p>This will freeze your browser. Be prepared to close the browser tab after running this.</p><p>This code completely blocks rendering. Since the call stack never empties, the browser never regains control and no rendering can occur. The page never updates.</p><p>So developers sliced work into smaller chunks to allow for breathing space for the browser to render:</p><pre>function update() {<br>  console.log(&quot;update&quot;);<br>}<br><br>function render() {<br>  console.log(&quot;render&quot;);<br>  const box = document.getElementById(&quot;box&quot;);<br>  box.textContent = `Updated at ${new Date().toLocaleTimeString()}`;<br>}<br><br>function loop() {<br>  update();<br>  render();<br>  setTimeout(loop, 16); // Use setTimeout() to chunk work<br>}<br>loop()</pre><p>While this doesn’t freeze the browser, be prepared to refresh the browser tab after running this.</p><p>Now, the page renders the updates (the time shown on the page updates) to the box content. Since most screens refresh at 60 Hz, 16 ms (1000 ms / 60 Hz) seemed like the right delay. This allowed the stack to clear between iterations so that the browser could render.</p><p>But this was still guesswork.</p><p>But this approach was not without its problems. First, timers are minimum delays, not guarantees. The callback may run for 20ms, 30ms or later. Also, if the callback took longer than 16ms, we would miss frames and accumulate jitter and drop frames. Consequently, the callback may run before or after the render.</p><p>Fundamentally, rendering is framed-based while timers are time-based, and therefore do not know when the browser is about to render.</p><h3><strong>Enter requestAnimationFrame</strong></h3><p>requestAnimationFrame solves exactly this problem:</p><pre>function update() {<br>  console.log(&quot;update&quot;);<br>}<br><br>function render() {<br>  console.log(&quot;render&quot;);<br>  const box = document.getElementById(&quot;box&quot;);<br>  box.textContent = &quot;Updated at &quot; + new Date().toLocaleTimeString();<br>}<br><br>function loop() {<br>  update();<br>  render();<br>  requestAnimationFrame(loop);<br>}<br>requestAnimationFrame(loop);</pre><p>This also doesn’t freeze the browser but be prepared to refresh the browser tab after running this.</p><p>As before, the page renders the updates on the page. However, unlike timers, this runs before rendering. This sounds great but where exactly does it fit in the event loop model? Let’s find out.</p><h3><strong>Test 1: Does requestAnimationFrame Cut Ahead of Microtasks?</strong></h3><p>If requestAnimationFrame runs just before rendering, it must not violate our previous rules:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});<br><br>requestAnimationFrame(() =&gt; {<br>  console.log(&quot;raf&quot;);<br>});</pre><p>The output in the console would be:</p><pre>microtask<br>raf</pre><p>As established, the browser does not render while microtasks are pending. Microtasks still run first and requestAnimationFrame does not change that.</p><h3><strong>Test 2: Is requestAnimationFrame Just Another Task?</strong></h3><p>If requestAnimationFrame were simply another macrotask, it would behave like setTimeout and follow the ordering of tasks:</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>}, 0);<br><br>requestAnimationFrame(() =&gt; {<br>  console.log(&quot;raf&quot;);<br>});<br><br>console.log(&quot;end&quot;);</pre><p>In practice, you will often see the following in the console:</p><pre>start<br>end<br>timeout<br>raf</pre><p>However, you may also see:</p><pre>start<br>end<br>raf<br>timeout</pre><p>The ordering is not guaranteed. Even if your environment consistently shows one ordering, the key point is that the model does not enforce it. The browser is allowed to process another task first, or perform a render before continuing with tasks. Because of this, there is no fixed ordering between setTimeout and requestAnimationFrame.</p><p>This might seem surprising. If requestAnimationFrame were just another macrotask, we would expect it to follow a consistent ordering relative to setTimeout. But it doesn’t, suggesting that requestAnimationFrame is not part of the task queue at all. Instead, it runs during the browser’s rendering phase, which is scheduled separately from tasks.</p><h3><strong>Test 3: Do Microtasks Inside requestAnimationFrame Run Before Paint?</strong></h3><p>What if requestAnimationFrame also created microtasks?</p><pre>requestAnimationFrame(() =&gt; {<br>  const box = document.getElementById(&quot;box&quot;);<br><br>  box.textContent = &quot;Frame start&quot;;<br><br>  Promise.resolve().then(() =&gt; {<br>    box.textContent = &quot;Microtask update&quot;;<br>  });<br>});</pre><p>The typical output is for the page to show “Microtask update”</p><p>When the requestAnimationFrame callback runs, the DOM updates and a microtask is queued. The requestAnimationFrame callback completes and microtasks drain. Only then can rendering occur.</p><p>Even inside requestAnimationFrame, microtasks must drain before rendering.</p><h3><strong>What requestAnimationFrame Actually Guarantees</strong></h3><p>requestAnimationFrame guarantees that the callback runs before the browser’s rendering. It runs at most once per frame and is aligned to the display’s actual refresh rate, regardless of whether it is 60Hz or 120Hz. It pauses automatically in background tabs and skips frames when the browser is busy.</p><h3><strong>The Complete Ordering</strong></h3><p>We can now state the model:</p><ol><li>Macrotask</li><li>Drain microtasks</li><li>requestAnimationFrame callbacks</li><li>Drain microtasks</li><li>Render</li></ol><p>This is the complete scheduling turn. Rendering is not part of task queue but is gated by it. requestAnimationFrame is the only public API designed to hook into that pre-render phase.</p><h3><strong>What This Prepares Us For Next</strong></h3><p>Now that we understand this structure, what do we do with it?</p><p>In the final article of this series, we move from mechanism to consequence:</p><p>What happens when a macrotask runs too long?</p><p>What happens when microtasks never stop?</p><p>Why does the UI freeze?</p><p>Why are some updates never visible?</p><p>Why do we sometimes need cleanup guards?</p><p>One we understand who gets to run and when, we can reason about performance, responsiveness and architectural trade-offs with precision.</p><p>This is where we go <a href="https://code.likeagirl.io/the-scheduling-boundaries-behind-responsive-ui-8f5804bcc0e8">next</a>.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/requestAnimationFrame"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66bf15b4e8a0" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/requestanimationframe-the-missing-scheduling-layer-66bf15b4e8a0">requestAnimationFrame: The Missing Scheduling Layer</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Thought Dark Mode Was Just a Toggle. It Turned Into a Full-System Refactor]]></title>
            <link>https://code.likeagirl.io/i-thought-dark-mode-was-just-a-toggle-it-turned-into-a-full-system-refactor-65fd49245482?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/65fd49245482</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Tue, 05 May 2026 19:19:44 GMT</pubDate>
            <atom:updated>2026-05-05T19:19:44.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDJz7_6ccVN6JvSOkmfX1Q.png" /></figure><p>My website was technically done. So I thought: <em>let’s just add one more thing</em>.</p><p>Dark mode.</p><p>Developers love that right? I didn’t even use that many colors — it should be quick to swap them around.</p><p>And yet, it turned into a full-system refactor: it was typography, code highlighting, images and rendering behavior.</p><h3><strong>The first problem: hardcoded colors</strong></h3><p>The problem showed up immediately: the few colors I used were hardcoded everywhere. A heading had one hex value, and a paragraph had another. Changing the theme meant updating each instance manually. No, thank you.</p><h4><strong>The fix</strong></h4><p>So I introduced CSS variables and defined colors by their roles.</p><ul><li>--text-primary</li><li>--text-secondary</li><li>--background-primary</li><li>--border</li></ul><p>With this, a heading wasn’t “black” anymore. It was text-primary. A background wasn’t “white”. It was background-primary.</p><p>This sounds like a small change but it fundamentally changed how I approached styling. I stopped thinking in terms of individual colors across themes and focused instead on the role and intention of each element, with color as just an implementation detail.</p><p>At this point, I thought I was mostly done. I wasn’t even close.</p><h3><strong>Dark mode is not black</strong></h3><p>With a color system in place, the next step seemed obvious and trivial: invert it. Just change black to white and white to black.</p><p>Except it looked terrible. Who would’ve thought that having white text on black would feel so… bright? It was harsh and fatiguing. Everything started blending together — almost like I had suddenly developed astigmatism.</p><p>Turns out dark mode isn’t black and white. Maximum contrast does not make text readable.</p><h4><strong><em>The fix</em></strong></h4><p>Shades of grey.</p><p>Instead of pure white, I switched to light grey and text was miraculously legible again. For secondary text, an even softer grey.</p><p>Good dark mode was about tuning contrast, making it proportionate and layered.</p><p>And that’s all my problems solved, said no one ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glqekcyiVR9xFqlyypkf-g.png" /><figcaption>White text on black was too much contrast on my screen. I felt it in my eyes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASj5KkNGBBruefO18FkQEw.png" /><figcaption>Subtle change to reduce contrast, making it easier to read over a longer period of time</figcaption></figure><h3><strong>Every surface breaks differently</strong></h3><p>Even after fixing colors, the UI was still inconsistent. Different parts of the website broke in different ways</p><h3><strong>Typography (Tailwind)</strong></h3><p>I was using Tailwind’s typography plugin (prose) for my writing pages. It worked well in light mode. But once I introduced my own variables, things started conflicting. Headings, links, and inline elements were all pulling from Tailwind’s internal color definitions instead of mine.</p><p>Some styles updated, others didn’t. Fixing one element would break another. The abstraction broke down, and the complexity I’d tried to hide came rushing back.</p><h4><strong><em>The fix</em></strong></h4><p>I explicitly mapped Tailwind’s typography variables to my own. Instead of relying on defaults, I treated typography as part of my system.</p><p>Once everything pointed back to the same set of variables, things became predictable again.</p><h3><strong>Code syntax highlighting</strong></h3><p>I use a lot of code snippets, especially in my <a href="https://www.marshateo.com/writing/javascript-event-loop-landing">JavaScript event loop article series</a>. Dark mode introduced a new inconsistency with code syntax highlighting:</p><ul><li>Github light theme was unreadable in dark mode</li><li>Github dark theme didn’t look great in light mode</li></ul><p>Who would’ve thought?</p><p>For a while, I assumed I had to pick one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*xRIOfPN-AiCOhgmtsAXXdQ.png" /><figcaption>Github’s light theme in dark mode was impossible to read</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*1esDSLSdRPbi-fMEcVllaA.png" /><figcaption>Github’s dark theme in light mode looked washed out</figcaption></figure><h4><strong><em>The fix</em></strong></h4><p>Use both and switch dynamically based on the mode. It sounds pretty obvious now, but at the time, I genuinely thought I had to choose.</p><h3><strong>Images</strong></h3><p>Images introduced a different kind of problem. Some worked fine. Others didn’t translate at all.</p><p>My hero image is of a sunrise. From the start, I imagined using a sunset version for dark mode. Did I create dark mode just so that I can use this image? Maybe.</p><p>Thankfully, this was easily implemented by including both images and switching between them based on the mode.</p><p>But my SVG diagrams were harder. I tried making their colors dynamic using CSS variables but it didn’t work reliably.</p><h4><strong><em>The fix</em></strong></h4><p>Instead of forcing everything to be dynamic, I created two versions of each diagram, one for each mode. It felt less elegant at first, but it worked better. Not everything should be dynamically styled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*vap9WXT_6CcSPznSKxPQ1w.gif" /><figcaption>Diagrams designed for light mode don’t translate automatically.</figcaption></figure><h3><strong>The problem wasn’t only styling — it was timing too</strong></h3><p>After fixing all that, I refreshed the page for my moment of victory. A flash of light mode appeared before it switched to dark. It was subtle, but definitely there. And yes, the temptation to pretend that didn’t happen was definitely there too.</p><p>The browser was rendering <strong>before </strong>the correct theme was applied. By the time JavaScript the correct theme was set, the browser had already painted the wrong one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*1ed2lo9VGwdHK27f4L1Jog.gif" /><figcaption>The flash: light mode renders before dark mode is applied</figcaption></figure><h4><strong><em>The fix</em></strong></h4><p>The theme needed to be determined before rendering. Moving the theme logic earlier removed the flash entirely. It was a small change technically, but it had a big impact on how the site felt.</p><h3><strong>What this changed for me</strong></h3><p>I thought I was adding a feature: a toggle button and a visual enhancement that sits on top of everything else.</p><p>But dark mode didn’t sit on top of my UI. It ran through it and every part of the system had to agree. None of the above was individually difficult. But together, they revealed that dark mode was a system and one that needs to be designed intentionally.</p><h3>If you’re implementing dark mode</h3><p>A few things I wish I knew earlier:</p><ul><li>Define colors by role, not value</li><li>Avoid extreme contrast</li><li>Treat typography as part of your system</li><li>Don’t force everything to be dynamic</li><li>Handle theme selection before render</li></ul><p>If you’re curious, the full implementation and visuals are on my <a href="https://www.marshateo.com/">site</a>. This article was also originally published <a href="https://www.marshateo.com/writing/portfolio-dark-mode">there</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65fd49245482" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/i-thought-dark-mode-was-just-a-toggle-it-turned-into-a-full-system-refactor-65fd49245482">I Thought Dark Mode Was Just a Toggle. It Turned Into a Full-System Refactor</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering Is a Browser Decision, Not a JavaScript One]]></title>
            <link>https://code.likeagirl.io/rendering-is-a-browser-decision-not-a-javascript-one-7a34f0b292c4?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a34f0b292c4</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 13:38:16 GMT</pubDate>
            <atom:updated>2026-05-15T08:20:04.765Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the fifth article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BzjH3zFkuUWHAFbwle_Eg.png" /></figure><p>You change the DOM.</p><p>You expect the screen to update.</p><p>It doesn’t.</p><p>Why?</p><p>In the earlier articles, we established three constraints:</p><ol><li>JavaScript runs to completion.</li><li>Tasks form scheduling boundaries.</li><li>Microtasks must fully drain before moving on.</li></ol><p>Now we add a fourth:</p><blockquote>The browser will not render while a macrotask is running nor while microtasks are draining.</blockquote><h3>Rendering Is a Browser Decision</h3><p>Up to this point in the series, we’ve focused on two pieces of the system:</p><ol><li>The JavaScript engine, which executes code and manages the call stack.</li><li>The runtime, which provides the event loop and scheduling rules.</li></ol><p>But neither of these is responsible for rendering.</p><p>Beyond the JavaScript engine and the runtime, the browser also contains a rendering engine — the subsystem responsible for layout and painting.</p><p>The engine executes your code. The runtime manages when that code runs. The rendering engine decides when the result becomes visible.</p><p>For simplicity, this article will refer to that rendering engine simply as the browser.</p><h3>The Rendering Misconception</h3><p>When I first started learning JavaScript, I carried several mental models that felt reasonable:</p><ul><li>DOM updates render immediately</li><li>If I change the UI, the user will see it right away.</li><li>The browser renders continuously at 60fps.</li></ul><p>These felt natural because the screen often updates quickly. But they’re incomplete: Rendering does not happen whenever the DOM changes. Instead, rendering happens only when there is a ‘safe opportunity’, after the current macrotask finishes and the microtask queue is empty.</p><p>Rendering is not triggered by DOM mutation. It is gated by scheduling boundaries. Let’s test that.</p><h3>Running the Experiments</h3><p>These experiments rely on the browser’s rendering behaviour.</p><ol><li>Create a simple HTML file with the following content:</li></ol><pre>&lt;div id=&quot;box&quot;&gt;Initial&lt;/div&gt;</pre><p>2. Open the file in your browser</p><p>3. You can run all code snippets in this series by pasting them into the browser console.</p><p>These examples will not work in Node.js because they depend on the DOM and browser rendering.</p><h3>Test 1: DOM Updates Inside One Macrotask</h3><p>What happens when we have multiple DOM updates within the same macrotask? We may write something like the following, using a placeholder before the final string is ready:</p><pre>const box = document.getElementById(&quot;box&quot;);<br><br>box.textContent = &quot;Temporary string&quot;;<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>box.textContent = &quot;Final string of Test 1&quot;;</pre><p>We might worry that &quot;Temporary string&quot; would briefly appear before &quot;Final string&quot; is ready. But that doesn&#39;t happen. Phew!</p><p>Both updates occur inside the same macrotask and the browser refuses to render mid-task. It waits until the entire macrotask is finished, checks that there is no microtask in the queue and finally considers rendering.</p><p>The intermediate DOM states never show.</p><h3>Test 2: Microtasks Also Delay Rendering</h3><p>What if the second update happens in a microtask instead? Would &quot;Temporary string&quot; appear briefly?</p><pre>const box = document.getElementById(&quot;box&quot;);<br><br>box.textContent = &quot;Temporary string&quot;;<br><br>Promise.resolve().then(() =&gt; {<br>  box.textContent = &quot;Final string of Test 2&quot;;<br>});</pre><p>Again, we only see &quot;Final string of Test 2&quot;.</p><p>The initial macrotask runs and sets &quot;Temporary string&quot;. After the call stack is empty, the microtask runs immediately after to update the DOM to &quot;Final string&quot;. Only now does the browser get an opportunity to render.</p><p>Microtasks delay rendering just like synchronous code does.</p><h3>Test 3: Breaking Into a New Task Allows Paint</h3><p>Now consider a timer callback:</p><pre>const box = document.getElementById(&quot;box&quot;);<br><br>box.textContent = &quot;Temporary string&quot;;<br><br>setTimeout(() =&gt; {<br>  box.textContent = &quot;Final string of Test 3&quot;;<br>}, 1000);</pre><p>This time we may see &quot;Temporary string&quot;, followed by &quot;Final string of Test 3&quot; a second later.</p><p>Unlike the previous tests, we have now introduced a task boundary. The browser finishes the initial macrotask, drains microtasks (there are none here) and gets an opportunity to render. If it chooses to render, &quot;Temporary string&quot; becomes visible.</p><p>Later, when the runtime schedules the timer’s macrotask, the DOM updates to &quot;Final string&quot; and the next render will reflect this.</p><p>Rendering is allowed at task boundaries. This does not mean that rendering is guaranteed between macrotasks; only that it can only happen there.</p><h3>Why Rendering Waits</h3><p>If the browser could render in the middle of a macrotask or in the middle of microtask draining, it could display half-updated DOM, inconsistent layout and/or partially computed state.</p><p>Thankfully, with this constraint, the browser renders only stable states, where a macrotask has finished and the microtask queue is empty. There would be no partial work in progress and hence rendering is atomic with respect to JavaScript execution.</p><h3>The Correct Mental Model</h3><p>With these tests, we’ve shown that the browser does not render whenever the DOM changes. Instead:</p><blockquote>The browser renders only after JavaScript finishes its turn.</blockquote><p>Here, a “turn” means the current macrotask completes and the microtask queue has been fully drained.</p><p>Rendering is allowed only at those boundaries. This does not mean the browser renders after every turn, only that it cannot render during one. The rendering decision is gated by the same scheduling rules we’ve been building throughout this series.</p><h3>What This Prepares Us For Next</h3><p>If rendering only happens at specific boundaries, a new question emerges: How do we write code that runs at the right moment?</p><p>setTimeout creates a new macrotask but it does not align with the browser&#39;s frame timing. Microtasks delay rendering but they do not schedule it. If we want smooth animation and responsive updates, we need a way to run code just before the browser renders the next frame.</p><p>This is what requestAnimationFrame is design for. In the <a href="https://code.likeagirl.io/requestanimationframe-the-missing-scheduling-layer-66bf15b4e8a0">next article</a>, we&#39;ll look more closely at how the browser&#39;s rendering cycle works and how to schedule work in harmony with it.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/rendering"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a34f0b292c4" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/rendering-is-a-browser-decision-not-a-javascript-one-7a34f0b292c4">Rendering Is a Browser Decision, Not a JavaScript One</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[async / await: Pausing a Function Without Pausing JavaScript]]></title>
            <link>https://javascript.plainenglish.io/async-await-pausing-a-function-without-pausing-javascript-5e3e2a68f1f2?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3e2a68f1f2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 06:32:23 GMT</pubDate>
            <atom:updated>2026-05-15T08:19:23.224Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the fourth article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPWAr5QhksYkqygtYTxI7g.png" /></figure><p>In the <a href="https://medium.com/@marshateo/microtasks-why-promises-run-first-37fd5642daca">last article</a>, we established a precise rule:</p><blockquote>Once a macrotask finishes, JavaScript drains all microtasks before selecting the next macrotask.</blockquote><p>Microtasks like Promises are continuations that must complete before the runtime moves on to the next macrotask. async/await is often described as syntactic sugar over Promises. If that’s the case, we should already understand how await works.</p><p>Let’s see.</p><h3><strong>The Possible Mental Models</strong></h3><p>Before we look at any code, consider this question: When JavaScript reaches await, what actually happens?</p><p>It’s surprisingly easy to carry one of the following mental models (I certainly did when I first started learning JavaScript). Which of these feel right?</p><p>a. await blocks the entire program before the value resolves, like sleep() in C or C++</p><p>b. await pauses the function and immediately yields to the event loop, creating a new macrotask</p><p>c. await splits the function and schedules the remainder as a microtask</p><p>Pause for a moment. Pick one and we’ll test it.</p><h3><strong>Running the Experiments</strong></h3><p>You can run all code snippets in this series by pasting them into the browser console.</p><p>While some examples work in Node.js, others rely on browser APIs (like rendering or requestAnimationFrame), so the browser is the most reliable environment.</p><h3><strong>Test for Mental Model A ( </strong><strong>await Blocks)</strong></h3><p>Let’s see if await pauses the entire program:</p><pre>async function test() {<br>  console.log(&quot;Inside test&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;After await&quot;);<br>}<br><br>console.log(&quot;Before test&quot;);<br>test();<br>console.log(&quot;After test&quot;);</pre><p>If await blocked the program, we would expect:</p><pre>Before test<br>Inside test<br>After await<br>After test</pre><p>Instead, we observe that After test runs before After await:</p><pre>Before test<br>Inside test<br>After test<br>After await</pre><p>It appears that await does not block JavaScript. Execution continues after calling test(). So whatever await does, it does not stop everything.</p><h3><strong>Test for Mental Model B ( await Yields)</strong></h3><p>Perhaps await pauses the function and immediately hands control back to the runtime for it to choose another macrotask:</p><pre>async function test() {<br>  console.log(&quot;Inside test&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;After await&quot;);<br>}<br><br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>console.log(&quot;Before test&quot;);<br>test();<br>console.log(&quot;After test&quot;);</pre><p>If await yielded control to the runtime and created a macrotask boundary, the timer might run first:</p><pre>Before test<br>Inside test<br>After test<br>timeout<br>After await</pre><p>But it never does. We instead observe:</p><pre>Before test<br>Inside test<br>After test<br>After await<br>timeout</pre><p>The continuation after await always runs before the timer. This matches the rule from the last article:</p><blockquote>Microtasks are drained before any macrotask is selected.</blockquote><p>await does not create a macrotask.</p><h3><strong>Mental Model C: The Only Survivor</strong></h3><p>So far, the only model consistent with every test is:</p><blockquote>When execution reaches await, the function pauses and the rest of the function is queued as a microtask.</blockquote><p>When JavaScript reaches await value, the engine conceptually performs something like:</p><p>1. Convert value into a Promise if it isn’t one already.</p><p>2. Wrap the rest of the function in a continuation.</p><p>3. Schedule the continuation as a microtask.</p><p>4. Return immediately to the caller.</p><p>The function simply splits at this point. This happens even if the value is already resolved:</p><pre>async function test() {<br>  console.log(&quot;Inside test&quot;);<br>  await 42;<br>  console.log(&quot;After await&quot;);<br>}<br><br>console.log(&quot;Before test&quot;);<br>test();<br>console.log(&quot;After test&quot;);</pre><p>We still observe:</p><pre>Before test<br>Inside test<br>After test<br>After await</pre><p>Even though 42 is not a promise, the remainder of the function runs later.</p><p>await will also split the function however many times it appears in the function. Consider:</p><pre>async function test() {<br>  console.log(&quot;Inside test&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;After first await&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;After second await&quot;);<br>}<br><br>console.log(&quot;Before test&quot;);<br>test();<br>console.log(&quot;After test&quot;);<br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);</pre><p>Observed:</p><pre>Before test<br>Inside test<br>After test<br>After first await<br>After second await<br>timeout</pre><p>Each await causes the function to split with each await creating a new continuation that runs as a microtask. Both continuations run before the timer since the runtime drains microtasks fully before scheduling the next macrotask.</p><p>That split results in a pause in the current async function. There is no other pause — not in the call stack, the event loop nor the entire program.</p><p>With await, control immediately returns to the caller. That’s why this works:</p><pre>async function loadData() {<br>  await fetch(&quot;/data&quot;);<br>  console.log(&quot;done&quot;);<br>}<br><br>console.log(&quot;start&quot;);<br>loadData();<br>console.log(&quot;continue&quot;);</pre><p>Output:</p><pre>start<br>continue<br>done</pre><p>The function pauses and the program continues.</p><h3><strong>async / await As Syntactic Sugar Over Promises</strong></h3><p>You may have heard that async/await is syntactic sugar over promises. That’s true, but only if we are precise what the sugar expands into. At its core, await is equivalent to calling .then() but with one addition.</p><p>When JavaScript reaches await value, it registers a continuation like .then() would but it also splits the current function at that point and schedules the remainder to run later as a microtask.</p><p>With raw .then(), you manually place the continuation inside a callback. With await, the language automatically pauses the function, preserves its local variables and control flow and resumes it later in the microtask queue. It is a function split backed by the microtask system.</p><blockquote>await is .then() plus structured function splitting and microtask resumption.</blockquote><h3><strong>What About async?</strong></h3><p>So far, we’ve focused entirely on await. But every example also had async. If await is responsible for splitting the function, what does async actually do? Let’s see.</p><pre>async function test() {<br>  return 42;<br>}<br><br>async function main() {<br>  const p1 = test();<br>  console.log(&quot;Without await:&quot;, p1);<br><br>  const p2 = await test();<br>  console.log(&quot;With await:&quot;, p2);<br>}<br><br>main();```javascript</pre><p>The output:</p><pre>Without await: Promise { 42 }<br>With await: 42</pre><p>The main() function runs synchronously until the first await. When test() is called without await, there is no pause and no microtask. The body of test() runs immediately. The only difference is that test() returns a Promise.</p><p>async on its own does not introduce asynchronous work. Instead, it changes the return type of the function: test() returns a Promise, even if it completes synchronously.</p><p>When test() is called with await, something different happens. The call to test() still runs immediately, and it still returns a Promise. But now main() pauses at the await. The remainder of main() is wrapped into a continuation and scheduled as a microtask. When that microtask runs, the Promise returned by test() is unwrapped and its resolved value becomes the value of the await expression.</p><p>Without await, p is a Promise. With await, p is the resolved value of that Promise.</p><h3><strong>The Correct Mental Model</strong></h3><p>We can now separate the two keywords clearly:</p><ul><li>async changes what the function returns.</li><li>await changes how the function executes.</li></ul><p>If there is no await, an async function can run entirely synchronously. If there is an await, the function splits and resumes as a microtask continuation.</p><p>Once you see this, async/await stops being mysterious. It becomes a thin layer over the microtask system.</p><h3><strong>What This Prepares Us For Next</strong></h3><p>We now understand:</p><ul><li>Macrotasks are chosen one at a time.</li><li>Microtasks drain completely.</li><li>Promise callbacks are continuations.</li><li>await creates microtask continuations.</li></ul><p>There is one more piece missing:</p><blockquote>When does rendering happen?</blockquote><p>To answer that we need to look beyond JavaScript execution and into the browser’s frame lifecycle. That is the next layer of the event loop, and that’s where we go <a href="https://medium.com/code-like-a-girl/rendering-is-a-browser-decision-not-a-javascript-one-7a34f0b292c4">next</a>.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/async-await"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3e2a68f1f2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/async-await-pausing-a-function-without-pausing-javascript-5e3e2a68f1f2">async / await: Pausing a Function Without Pausing JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microtasks: Why Promises Run First]]></title>
            <link>https://javascript.plainenglish.io/microtasks-why-promises-run-first-37fd5642daca?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/37fd5642daca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 05:48:14 GMT</pubDate>
            <atom:updated>2026-04-27T06:33:38.333Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the third article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVilrTpHR6EmyatmC29FLA.png" /></figure><p>In the <a href="https://medium.com/@marshateo/macrotasks-what-a-task-actually-is-e194ee84859f">last article</a>, we established that:</p><blockquote>JavaScript execution cannot be interrupted.</blockquote><p>Once a macrotask starts, nothing cuts in. Only after it completes does the runtime select the next macrotask from the queue.</p><p>But consider this:</p><pre>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;promise&quot;));<br><br>console.log(&quot;sync done&quot;);</pre><p>The output is always:</p><pre>sync done<br>promise<br>timeout</pre><p>Both setTimeout and Promise.then are asynchronous and both schedule work to run later. If macrotasks are chosen one at a time, and nothing interrupts them, then promises should behave like timers. But that’s not the case. The promise runs first, every time. Why?</p><p>If our macrotask model of JavaScript were complete, this ordering would not be guaranteed. Something else must exist. Specifically, there is another category of work in JavaScript: <strong>microtasks</strong>.</p><p>They do not interrupt the current macrotask. And yet they run before the runtime selects the next macrotask. Before we define them fully, we should understand why such a mechanism is needed.</p><h3><strong>The Tempting but Incomplete Explanation</strong></h3><p>Many explanations jump immediately to:</p><blockquote>“Promises use the microtask queue, which runs before the macrotask queue.”</blockquote><p>That statement is technically correct. But it explains nothing. Why are there two queues? Why does one outrank the other?</p><p>If we stop here, microtasks feel arbitrary. Let’s instead find out more.</p><h3><strong>Running the Experiments</strong></h3><p>You can run all code snippets in this series by pasting them into the browser console.</p><p>While some examples work in Node.js, others rely on browser APIs (like rendering or requestAnimationFrame), so the browser is the most reliable environment.</p><h3><strong>A Hypothesis: Promises Are Just Higher-Priority Tasks</strong></h3><p>A reasonable mental model is that microtasks are just higher-priority tasks. When we have timers and promises, timers go into one queue, promises go into another, and the promise queue is checked first.</p><p>Let’s test this:</p><pre>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise 1&quot;);<br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;promise 2&quot;);<br>  });<br>});<br><br>console.log(&quot;sync done&quot;);</pre><p>If promises are merely higher-priority tasks, we may expect:</p><pre>sync done<br>promise 1<br>timeout<br>promise 2</pre><p>After sync done, the runtime has at least two pending pieces of work: the timer callback and the first promise callback. Since promise callbacks have higher priority, the runtime chooses the promise first. Consequently, promise 1 runs before timeout.</p><p>When promise 1 runs, it schedules another promise callback: promise 2. At this point, the runtime could choose between the existing timer callback or the newly scheduled promise callback. If promise callbacks were just higher priority macrotasks, the runtime should be free to interleave them.</p><p>However, the actual output is:</p><pre>sync done<br>promise 1<br>promise 2<br>timeout</pre><p>promise 2 runs immediately after promise 1, before the timeout is even considered.</p><h3><strong>The Rule That Must Exist</strong></h3><p>The only model consistent with this behavior is:</p><blockquote>Once microtask execution begins, all microtasks must run to completion before the runtime considers another macrotask.</blockquote><p>Promise callbacks are not independent tasks competing with timers. They are unfinished work from the current turn of execution. They are continuations and continuations must complete before control is returned to the runtime.</p><h3><strong>Reframing Microtasks Properly</strong></h3><p>A microtask is not a faster callback nor is it a convenience queue. Promise callbacks are the most common example of microtasks, but this mechanism also underlie async functions and MutationObserver callbacks. Broadly, a microtask is:</p><blockquote>Work that must be completed before JavaScript yields control back to the runtime.</blockquote><p>This is why:</p><ul><li>microtasks run after the current macrotask finishes,</li><li>microtasks run before the runtime chooses another macrotask,</li><li>the runtime drains the microtask queue completely,</li><li>microtasks can schedule more microtasks,</li></ul><p>They exist to preserve atomicity across asynchronous boundaries.</p><h3><strong>Why This Rule Must Exist</strong></h3><p>If microtasks were treated like ordinary macrotasks, promise chains could interleave with unrelated work. That would introduce subtle inconsistencies and expose partially completed state.</p><p>Consider this:</p><pre>let state = {<br>  loading: true,<br>  data: null<br>};<br><br>Promise.resolve().then(() =&gt; {<br>  state.data = &quot;result&quot;;<br>  state.loading = false;<br>});</pre><p>This callback represents a single logical transition where the data arrives and loading ends. From the programmer’s perspective, these two assignments belong together.</p><p>If the runtime were allowed to pause this callback midway or run unrelated macrotasks before it completes, external code could observe:</p><pre>{ loading: true, data: &quot;result&quot; }</pre><p>This is a partially completed update (data has arrived but loading is still true). JavaScript avoids this by enforcing:</p><blockquote>Once the current macrotask finishes, the runtime runs all microtasks run before selecting another macrotask.</blockquote><p>This ensures that promises are continuations of the current turn of execution. And these continuations must complete before control returns to the runtime. That guarantee makes promise chains predictable:</p><pre>Promise.resolve()<br>  .then(() =&gt; step1())<br>  .then(() =&gt; step2());</pre><p>The first .then() callback is queued as a microtask. After the promise returned by step1() settles, the second callback is queued. A promise chain schedules its continuations incrementally, not all at once.</p><p>Yet because the runtime must drain the microtask queue completely before selecting another macrotask, these incrementally scheduled callbacks still run back-to-back, without unrelated timers or events cutting in between them. The continuation may be deferred but it is never fragmented.</p><h3><strong>The Draining Behavior</strong></h3><p>Microtasks are not executed one-by-one with runtime checks between them. They are drained in a loop:</p><pre>while (microtask queue is not empty) {<br>  run next microtask<br>}</pre><p>That is why nested promises run immediately. That is why infinite promise loops freeze the page. Consider:</p><pre>function loop() {<br>  Promise.resolve().then(loop);<br>}<br><br>setTimeout(() =&gt; console.log(&quot;timeout fired&quot;), 0);<br><br>loop();</pre><p>If you run this, be prepared to close the page, since this experiment creates an infinite microtask loop.</p><p>The page would freeze and timeout fired is never logged since a new microtask is queued every time loop is called. The runtime is not allowed to proceed to another macrotask while microtasks remain. Microtasks are not candidates for task selection. They are executed automatically as part of finishing the current turn.</p><h3><strong>The JavaScript Turn Model</strong></h3><p>We can now describe a single turn of JavaScript execution:</p><p>1. The runtime chooses a macrotask.</p><p>2. JavaScript executes synchronously.</p><p>3. Once the call stack is empty, the runtime drains the microtask queue.</p><p>4. Only then can the runtime consider another macrotask.</p><p>This is the event loop from JavaScript’s perspective. In later articles, we will extend this model to include rendering and the browser’s frame lifecycle. loop.</p><h3><strong>The Mental Model to Keep</strong></h3><p>When debugging async behavior, ask:</p><ul><li>Did we just finish a macrotask?</li><li>Are there microtasks pending?</li><li>Has the runtime been allowed to choose another macrotask yet?</li></ul><p>If microtasks exist, the answer is always:</p><blockquote>No, the runtime must wait.</blockquote><h3><strong>What This Prepares Us For Next</strong></h3><p>If microtasks are mandatory continuations, then what exactly does await do?</p><p>Does it pause execution?</p><p>Does it create a new task?</p><p>Or does it quietly hook into this same microtask mechanism?</p><p>Understanding that requires looking at async functions more closely.</p><p>That is the subject of the <a href="https://medium.com/@marshateo/async-await-pausing-a-function-without-pausing-javascript-5e3e2a68f1f2">next article</a>.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/microtasks"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37fd5642daca" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/microtasks-why-promises-run-first-37fd5642daca">Microtasks: Why Promises Run First</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Macrotasks: What a Task Actually Is]]></title>
            <link>https://javascript.plainenglish.io/macrotasks-what-a-task-actually-is-e194ee84859f?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e194ee84859f</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 13:42:06 GMT</pubDate>
            <atom:updated>2026-04-23T05:49:05.370Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the second article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGW9tQzD-YdsAV4APb6iWg.png" /></figure><p>In the <a href="https://medium.com/@marshateo/the-javascript-runtime-fixing-the-mental-model-75ccdc08aaca">previous article</a>, we established that</p><blockquote>JavaScript executes synchronously inside a task, and nothing can interrupt that execution.</blockquote><p>This explains why timers don’t cut in, why promises wait and why loops block everything else. But if JavaScript runs ‘inside a task’, where does that task begin and end? Is the entire script one task? Is each function call its own task?</p><p>This article exists to answer more precisely:</p><blockquote>What exactly is a task?</blockquote><h3><strong>The Wrong Mental Model of a Task</strong></h3><p>You would think that ‘task’ refers to a unit of work — something with a duration, a beginning, and an end — and imagine that in JavaScript, a ‘task’ refers to a big chunk of execution. Maybe each statement is its own task; Each function call creates a new task; Control-flow disruptions using try/catch create task boundaries where the runtime is allowed to pause the current execution to run something else. With this, synchronous code consists of smaller tasks, and execution could be subdivided internally.</p><p>Let’s test that idea.</p><h3><strong>Running the Experiments</strong></h3><p>You can run all code snippets in this series by pasting them into the browser console.</p><p>While some examples work in Node.js, others rely on browser APIs (like rendering or requestAnimationFrame), so the browser is the most reliable environment.</p><h3><strong>Test 1: The Initial Script Is One Task</strong></h3><p>In the <a href="https://medium.com/@marshateo/the-javascript-runtime-fixing-the-mental-model-75ccdc08aaca">previous article</a>, we tested whether setTimeout could interrupt synchronous execution:</p><pre>console.log(&quot;sync start&quot;);<br><br>// Schedule asynchronous callback with setTimeout<br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout fired&quot;);<br>}, 0);<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>console.log(&quot;sync end&quot;);</pre><p>What we always observed was:</p><pre>sync start<br>sync end<br>timeout fired</pre><p>The entire global script executed as one uninterrupted block. The setTimeout callback ran later in a separate execution window. There are 2 tasks here: the initial script and the timeout callback.</p><p>Even though the timer expired quickly, the callback did not execute immediately. Instead, when the timer expired, the callback became eligible to run and waited in the queue managed by the runtime.</p><h3><strong>Test 2: Internal Structure Does Not Create Task Boundaries</strong></h3><p>Could each function call be its own ‘task’ internally? If function calls created new tasks, the runtime could switch between them.</p><pre>function a() {<br>  console.log(&quot;a&quot;);<br>  b();<br>}<br><br>function b() {<br>  console.log(&quot;b&quot;);<br>  c();<br>}<br><br>function c() {<br>  console.log(&quot;c&quot;);<br>}<br><br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>a();</pre><p>If function calls created new tasks, we might expect the timeout to run between a, b, or c.</p><p>But the output is always:</p><pre>a<br>b<br>c<br>timeout</pre><p>Even though the call stack grows and shrinks, JavaScript remains inside the same task the entire time. Function calls change the call stack but do not create new tasks because these changes to the internal call stack are invisible to the runtime. The runtime only observes whether the call stack is empty.</p><p>This is the case even in deep recursion cases:</p><pre>console.log(&quot;start&quot;)<br><br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>function recurse(n) {<br>  if (n === 0) return ;<br>  recurse(n - 1);<br>}<br><br>recurse(100);<br><br>console.log(&quot;end&quot;);</pre><p>The runtime does not care how long the call stack is:</p><pre>start<br>end<br>timeout</pre><h3><strong>Test 3: Exceptions Do Not Create Task Boundaries</strong></h3><p>Perhaps abrupt control flow — like exceptions — creates a task boundary. Maybe now execution ‘breaks’ enough that the runtime gets a chance to run something else.</p><pre>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>try {<br>  console.log(&quot;before throw&quot;);<br>  throw new Error(&quot;boom&quot;);<br>} catch {<br>  console.log(&quot;caught error&quot;);<br>}<br><br>console.log(&quot;after catch&quot;);</pre><p>The output is always:</p><pre>before throw<br>caught error<br>after catch<br>timeout</pre><p>Even though execution jumps abruptly from throw to catch, it never leaves the current task. JavaScript remains in the same task until after catch and the runtime schedules the timer callback task.</p><p>Now let’s remove the try/catch:</p><pre>setTimeout(() =&gt; console.log(&quot;timeout task&quot;), 0);<br><br>function a() {<br>  console.log(&quot;a: enter&quot;);<br>  try {<br>    b();<br>  } finally {<br>    console.log(&quot;a: finally (ran during unwind)&quot;);<br>  }<br>  console.log(&quot;a: after b (never)&quot;);<br>}<br><br>function b() {<br>  console.log(&quot;b: enter&quot;);<br>  try {<br>    c();<br>  } finally {<br>    console.log(&quot;b: finally (ran during unwind)&quot;);<br>  }<br>}<br><br>function c() {<br>  console.log(&quot;c: throw&quot;);<br>  throw new Error(&quot;boom&quot;);<br>}<br><br>a();<br>console.log(&quot;global: after a (never)&quot;);</pre><p>What happens?</p><pre>a: enter<br>b: enter<br>c: throw<br>b: finally (ran during unwind)<br>a: finally (ran during unwind)<br>Uncaught Error: boom<br>timeout task</pre><p>Control never returns to a: after b or global: after a after the exception was thrown. The current task terminates immediately when the error escapes the call stack. As the stack unwinds, the finally blocks run. Only after the unwind is complete does the runtime regain control and select select the next task. An uncaught exception ends the current task. It does not subdivide it.</p><h3><strong>Test 4: User Events Do Not Interrupt</strong></h3><p>Now let’s introduce an external event: a user click.</p><pre>document.addEventListener(&quot;click&quot;, () =&gt; {<br>  console.log(&quot;click handler ran&quot;);<br>});<br><br>console.log(&quot;start long task&quot;);<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>console.log(&quot;end long task&quot;);</pre><p>If you click the page while the loop is running, what happens?</p><p>The page will appear frozen for a few seconds (the loop typically takes a couple of seconds to complete on most machines). The click is detected instantly by the browser but the click handler does not run. Only after the loop finishes do you see:</p><pre>start long task<br>end long task<br>click handler ran</pre><p>The click created a new task: the runtime (the browser) captured the click event and scheduled the task. That task waits for the engine to become idle.</p><h3><strong>Reframing Tasks Correctly: Permission, Not Duration</strong></h3><blockquote>A task describes why JavaScript is allowed to start running at all.</blockquote><p>The runtime (the browser or Node.js) observes events outside the JavaScript engine. These events include timers expiring and user interactions. Each of these produces a request to run JavaScript. A task is that request.</p><p>A task does not describe how long JavaScript runs. It describes an entry point into execution. For instance, the delay passed to setTimeout is a minimum delay, not a guaranteed execution time. When the timer expires, the callback becomes eligible to run. It does not execute immediately. It must still wait for the current task to finish and for the call stack to become empty.</p><p>When the call stack is empty, the runtime chooses one task and hands control to the engine. The JavaScript engine then runs that task synchronously to completion.</p><p>From the runtime’s point of view, the engine is either running or idle. An empty call stack is the only signal that matters. The runtime is free to wait, listen, and prepare callbacks — but it is not free to execute them whenever it likes. It must wait until JavaScript stops.</p><p>Tasks are a coordination mechanism between the runtime and the engine.</p><h3><strong>Why These Are Called “Macrotasks”</strong></h3><p>The kind of task we have been discussing has a more precise name: <strong>macrotask</strong>. Examples include the initial script execution, a setTimeout callback and a user event handler.</p><p>“Macro” does not mean large nor long-running. It distinguishes these tasks from another scheduling mechanisms we will introduce in the next article.</p><p>For now, a macrotask is:</p><blockquote>a request from runtime that allows the engine to begin executing code.</blockquote><h3><strong>The Runtime Model</strong></h3><p>At this point, we can describe the system precisely:</p><ul><li>The runtime collects requests to run JavaScript.</li><li>Each request is a macrotask.</li><li>When the call stack is empty, the runtime selects a macrotask.</li><li>JavaScript runs synchronously to completion.</li><li>Only then can another macrotask be considered.</li></ul><p>From the runtime’s perspective, the only thing that matters is whether the call stack is empty.</p><p>This explains why task boundaries are coarse. Task boundaries do not occur between statements, function calls, loop iterations, recursive calls nor try/catch blocks. They occur at large structural entry points like an entire script, an entire event handler, or an entire timer callback. The runtime does not see internal structure; It only sees whether execution has finished.</p><h3><strong>Where We Go Next</strong></h3><p>At this point, we know that a macrotask runs to completion. But what happens when, inside a macrotask, the code schedules more work that logically belongs to the same operation?</p><p>Should it interrupt the current macrotask? (But we just established that this is not possible).</p><p>Should it wait behind the other tasks in the queue? (But this would delay it unpredictably.)</p><p>Neither is ideal. Instead, JavaScript has a mechanism that does not interrupt the current macrotask but runs <strong>before</strong> the runtime selects the next macrotask. This mechanism is <strong>microtasks</strong>.</p><p>This is where we go <a href="https://medium.com/@marshateo/microtasks-why-promises-run-first-37fd5642daca">next</a>.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/macrotasks"><em>website</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e194ee84859f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/macrotasks-what-a-task-actually-is-e194ee84859f">Macrotasks: What a Task Actually Is</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Runtime: Fixing the Mental Model]]></title>
            <link>https://javascript.plainenglish.io/the-javascript-runtime-fixing-the-mental-model-75ccdc08aaca?source=rss-4efda1f7b8d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ccdc08aaca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Marsha Teo]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 20:10:17 GMT</pubDate>
            <atom:updated>2026-04-22T06:44:19.032Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the first article in a series on how JavaScript actually runs. You can read the full series </em><a href="https://medium.com/@marshateo/javascript-event-loop-series-building-the-event-loop-mental-model-from-experiments-fc1accf31223"><em>here</em></a><em> or on my </em><a href="https://www.marshateo.com/writing/javascript-event-loop-landing"><em>website</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92bMcTqNArflpl-RcUJZsg.png" /></figure><p>Most explanations of JavaScript’s event loop start with:</p><blockquote>JavaScript is single-threaded.</blockquote><p>This statement is technically true but doesn’t explain certain behaviors in JavaScript you may have noticed:</p><ul><li>setTimeout doesn’t interrupt loops after the timer has run out</li><li>setTimeout doesn’t block (like sleep(1) in C)</li><li>A resolved Promise still runs after synchronous code</li><li>await pauses a function but doesn’t freeze the page</li><li>Rendering sometimes wait</li></ul><p>So we’re left asking:</p><ul><li>Why didn’t my timeout fire?</li><li>Why didn’t it interrupt my loop?</li><li>Why does await pause <em>this</em> but not <em>everything</em>?</li><li>Why does nothing ever ‘cut in’?</li></ul><p>In this series, we’ll build the understanding needed to make JavaScript stop feeling magical.</p><p>Today’s core claim is simple:</p><blockquote>JavaScript executes synchronously inside a task, and nothing can interrupt that execution.</blockquote><h3><strong>What Does “Synchronous” and “Asynchronous” Really Mean?</strong></h3><p>First, let’s define ‘synchronous’ and ‘asynchronous’ precisely.</p><p>Synchronous execution refers to code that runs immediately, executing from top to bottom via the call stack. We will show that this cannot be interrupted in JavaScript.</p><p>By contrast, asynchronous code refers to code whose result is not available immediately. Some work is initiated now, but its continuation runs later. In practice, this almost always involves a <strong>callback</strong> — a function that is scheduled to execute in the future. In JavaScript, asynchronous code includes not only async/await but also other mechanisms like setTimeout, Promise, and requestAnimationFrame.</p><p>As this series will make clear, asynchronous mechanisms do not block nor interrupt the call stack. Instead, they arrange for something to run later via scheduling.</p><p>For now, let’s test the claim directly:</p><blockquote>Can asynchronous callbacks interrupt synchronous execution?</blockquote><h3><strong>Running the Experiments</strong></h3><p>You can run all code snippets in this series by pasting them into the browser console.</p><p>While some examples work in Node.js, others rely on browser APIs (like rendering or requestAnimationFrame), so the browser is the most reliable environment.</p><h3><strong>Baseline Case: Pure Synchronous Execution</strong></h3><p>Let’s start with a simple for loop:</p><pre>console.log(&quot;sync start&quot;);<br>for (let i = 0; i &lt; 1e9; i++) {}<br>console.log(&quot;sync end&quot;);</pre><p>The code runs from top to bottom. The output is unsurprisingly:</p><pre>sync start<br>sync end</pre><h3><strong>Test 1: Can setTimeout Interrupt a Loop?</strong></h3><p>Let’s introduce an asynchronous mechanism with setTimeout:</p><pre>console.log(&quot;sync start&quot;);<br><br>// Schedule asynchronous callback with setTimeout<br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout fired&quot;);<br>}, 0);<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>console.log(&quot;sync end&quot;);</pre><p>If setTimeout could interrupt, we would see:</p><pre>sync start<br>timeout fired<br>sync end</pre><p>But what actually happens is this:</p><pre>sync start<br>sync end<br>timeout fired</pre><p>The timer did not ‘cut in’: It waited until the loop finished running.</p><h3><strong>Test 2: Can Promises Interrupt?</strong></h3><p>Now let’s try a Promise:</p><pre>console.log(&quot;sync start&quot;);<br><br>// Schedule asynchronous callback with a Promise<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise callback&quot;);<br>});<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>console.log(&quot;sync end&quot;);</pre><p>If Promises could interrupt execution, we would see:</p><pre>sync start<br>promise callback<br>sync end</pre><p>But the observed behavior is:</p><pre>sync start<br>sync end<br>promise callback</pre><p>Even a resolved Promise does not interrupt synchronous execution. Once JavaScript starts running, it runs to completion.</p><h3><strong>Destroying the Wrong Mental Models</strong></h3><p>It’s easy to imagine JavaScript like this:</p><blockquote>JavaScript is running, but timers or promises can interrupt it when they’re ready</blockquote><p>In other words, setTimeout fires when ready and Promise callbacks can cut in once resolved.</p><p>This resembles signal handlers in C where a signal can interrupt a running program, jump to the handler function and then resume execution afterward. That is pre-emptive behavior where execution can be paused at arbitrary instruction boundaries and control temporarily transferred elsewhere. JavaScript does not behave this way.</p><p>We may also hold the mental model that:</p><blockquote>Timers or promises run JavaScript on another thread.</blockquote><p>In this model, JavaScript runs concurrently in multiple threads: The script is running on one thread; Timers run in a background thread; Promises resolve in another (or the same) background thread. If that were true, we would see interleaved console output.</p><p>However, in both tests, there is no interruption nor interleaved output between sync start and sync end in the console. These tests force us to accept that JavaScript execution is not pre-emptive. When JavaScript starts executing a task, it continues until the call stack is empty. Only then can anything else run JavaScript. Asynchronous work waits and queues.</p><h3><strong>But Where Does Asynchronous Work Wait?</strong></h3><p>JavaScript’s behavior makes more sense when you realize that when you run JavaScript in the browser, you are not just running a language. You are running two cooperating systems: the JavaScript <strong>Engine</strong> and the JavaScript <strong>Runtime Environment</strong>.</p><p>The engine (V8 in Chrome/Node, SpiderMonkey in Firefox, JavaScriptCore in Safari) parses and compiles code, manages memory and executes functions via the call stack. When we say “JavaScript runs”, we are referring to the engine. It knows variables, functions and the call stack. It does <strong>not</strong> know timers, the DOM, HTTP requests nor rendering.</p><p>Everything else is handled by the runtime (the browser or Node). For instance, the runtime provides web APIs (setTimeout, fetch, DOM events). Importantly, it also performs the asynchronous work <em>outside</em> the engine and decides when JavaScript is allowed to run again. This is the missing link:</p><blockquote>The engine executes. The runtime schedules.</blockquote><p>Let’s revisit our first experiment:</p><pre>console.log(&quot;sync start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout fired&quot;);<br>}, 0);<br><br>for (let i = 0; i &lt; 1e9; i++) {}<br><br>console.log(&quot;sync end&quot;);</pre><p>While the loop is running, what is happening structurally?</p><pre>┌───────────────────────────────┐  ┌───────────────────────────────┐<br>│         CALL STACK            │  │         TASK QUEUE            │<br>├───────────────────────────────┤  ├───────────────────────────────┤<br>│ for loop                      │  │ timeout callback (waiting)    │<br>│ global script                 │  |                               | <br>└───────────────────────────────┘  └───────────────────────────────┘</pre><p>The for loop occupies the call stack. Even after the timer has expired, its callback doesn’t interrupt the call stack. Instead, it waits in a queue managed by the runtime. The engine cannot run it (nor anything new) because the call stack is not empty. More broadly, the runtime schedules what the engine executes while the engine just executes whatever gets placed on the stack.</p><h3><strong>Introducing Tasks</strong></h3><p>When the runtime grants permission for the engine to execute JavaScript, that moment is an entry point into execution. This entry point or permission to run JavaScript is called a <strong>task</strong>. Examples include the initial script execution and the setTimeout callback. Once a task starts, JavaScript runs synchronously. Asynchronous mechanisms do not interrupt a task but instead schedules future tasks.</p><p>No worries if this doesn’t make complete sense yet. We will refine “task” in later articles. For now, this is enough.</p><h3><strong>What This Sets Up</strong></h3><p>From this article, we have established:</p><ul><li>JavaScript runs synchronously inside a task</li><li>Nothing can interrupt that execution</li><li>Asynchronous mechanisms do not cut in. They schedule.</li></ul><p>But if asynchronous callbacks don’t interrupt running code, how and when are they allowed to run? What exactly is a ‘task’? Where are these queues? Who decides what runs next?</p><p>This is the subject of the <a href="https://medium.com/@marshateo/macrotasks-what-a-task-actually-is-e194ee84859f">next article</a>.</p><p><em>This article was originally published on my </em><a href="https://www.marshateo.com/writing/runtime-mental-model"><em>website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ccdc08aaca" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-javascript-runtime-fixing-the-mental-model-75ccdc08aaca">The JavaScript Runtime: Fixing the Mental Model</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>