<?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 Umer Naeem on Medium]]></title>
        <description><![CDATA[Stories by Umer Naeem on Medium]]></description>
        <link>https://medium.com/@umerxzubairy?source=rss-8e1e400c5544------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KiebdiXQZDXWQcYNRdIQLA.jpeg</url>
            <title>Stories by Umer Naeem on Medium</title>
            <link>https://medium.com/@umerxzubairy?source=rss-8e1e400c5544------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:12:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umerxzubairy/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[Understanding Binary Tree Traversals]]></title>
            <link>https://umerxzubairy.medium.com/understanding-binary-tree-traversals-5c430ada3186?source=rss-8e1e400c5544------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c430ada3186</guid>
            <category><![CDATA[binary-tree-traversal]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Umer Naeem]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 10:22:55 GMT</pubDate>
            <atom:updated>2026-10-09T10:35:31.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOBpcVAvrfeSsNrM20didw.png" /></figure><p>Binary tree traversals have a reputation for being one of the hardest topics in DSA. For a long time, I had them crammed rather than understood. I could write the code from memory, but I couldn’t explain why it worked or when to pick one approach over another.</p><p>So one day I sat down and, with the help of Claude, broke the topic into small concepts until each one clicked. This guide is the result.</p><p>It’s five short lessons. Each ends with a quick <strong>Check yourself</strong> question, and the answers are at the very end. Instead of full solutions, every traversal comes with a <strong>template</strong>, so you write the code yourself.</p><p><strong>Try it as you read:</strong> the test harness is embedded at the end of this post. Copy it, write each traversal yourself, and run it against nine test trees. The animations along the way show each algorithm step by step.</p><p><strong>Contents</strong></p><ol><li>Foundations</li><li>Recursion and the call stack</li><li>Recursive DFS (pre, in, post)</li><li>Iterative DFS (your own stack)</li><li>BFS (level order)</li><li>Try it yourself</li></ol><h3>Lesson 1: Foundations</h3><h3>What is a binary tree?</h3><p>A tree where each node has <strong>at most two children</strong>. A node only knows three things:</p><ul><li>its <strong>value</strong></li><li>its <strong>left</strong> child</li><li>its <strong>right</strong> child</li></ul><p>It doesn’t know its parent or its siblings. To see everything, you have to walk there, and that’s why we need traversal strategies.</p><h3>Two ways to explore</h3><p><strong>DFS: Depth-First Search (stack).</strong> Keep going deeper until you run out of nodes, then back up and take the other path. A <strong>stack</strong> is last in, first out (LIFO), so the most recently discovered child is explored next, along with its children.</p><p><strong>BFS: Breadth-First Search (queue).</strong> Visit nodes <strong>level by level</strong>. A <strong>queue</strong> is first in, first out (FIFO), so it processes the <em>oldest</em> element first and nodes are handled in the order they were added.</p><p>The key insight: DFS and BFS are nearly the same algorithm. Swap the stack for a queue and DFS becomes BFS.</p><h3>Iterative vs. recursive</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e630d1f69f6814a4a16ef6e628a6df7/href">https://medium.com/media/9e630d1f69f6814a4a16ef6e628a6df7/href</a></iframe><h3>DFS orders: pre vs. in vs. post</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d835c6883fd637edd0a71728b3f1d214/href">https://medium.com/media/d835c6883fd637edd0a71728b3f1d214/href</a></iframe><p>Here’s the example tree used throughout this guide:</p><pre>        1          ← root<br>       / \<br>      2   3<br>     / \   \<br>    4   5   6      ← leaves (no children)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8d77c2b77c1586162be0eb49c48655a/href">https://medium.com/media/b8d77c2b77c1586162be0eb49c48655a/href</a></iframe><h3>When to use BFS vs. DFS</h3><p>Use <strong>BFS</strong> when you need:</p><ul><li>the shortest path, or the fewest steps</li><li>level-by-level answers (level order, right-side view, minimum depth)</li></ul><p>Use <strong>DFS</strong> when you need:</p><ul><li>to explore an entire path (root to leaf)</li><li>an answer that depends on a node’s children (height, diameter, balance)</li><li>a BST in sorted order (in-order traversal)</li></ul><p>Memory differs too: DFS holds about one path at a time (grows with the tree’s <strong>height</strong>), while BFS holds a whole level at a time (grows with the tree’s <strong>widest level</strong>).</p><h3>Recursion vs. iteration</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1141bcba8c1e9cd76a6c5e3b6fbbdcb/href">https://medium.com/media/a1141bcba8c1e9cd76a6c5e3b6fbbdcb/href</a></iframe><p><strong>Check yourself 1:</strong> You need the fewest steps from the root to any node with value 42. DFS or BFS?</p><h3>Lesson 2: Recursion and the Call Stack</h3><h3>What does a recursive function need?</h3><p>Imagine you’re in a dark movie theater and want to know your row. You ask the person in front of you, who asks the person in front of them, until someone in row 1 says “I’m in row 1!” Then the answers flow back: 2, 3, 4… That’s recursion.</p><p>Every recursive function needs two things:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/377fecfac35e124cb86c81310a7c095f/href">https://medium.com/media/377fecfac35e124cb86c81310a7c095f/href</a></iframe><h3>The “leap of faith”</h3><p>Trust the process. Don’t trace how every call resolves. Instead:</p><ol><li>Handle the <strong>base case</strong>.</li><li><strong>Call</strong> the function on the children (smaller problems), and trust that they return the right answer.</li><li><strong>Combine</strong> their results with your own.</li></ol><h3>Example: the call stack</h3><pre>Going DOWN (asking)                  Coming back UP (answering)<br><br>            [row1] ← base case!      [row1] returns 1       → popped<br>        [row2]                       [row2] returns 1+1 = 2 → popped<br>    [row3]                           [row3] returns 2+1 = 3 → popped<br>[row4: you]                          [row4] returns 3+1 = 4 → popped ✅</pre><p>Each call is <strong>pushed</strong> onto the stack on the way down and <strong>popped</strong> on the way up. Last in, first out: the call stack is a stack.</p><h3>The big connection: “on the way down” vs. “on the way up”</h3><p>You can process a node either on the way <strong>down</strong> or on the way <strong>up</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75f03ef4fed5ca7cd83df87dd514e3f8/href">https://medium.com/media/75f03ef4fed5ca7cd83df87dd514e3f8/href</a></iframe><h3>Which way does the information flow?</h3><p>When you’re stuck on a problem, ask where the information comes from:</p><ul><li><strong>From the parent</strong> (“what’s above me?”, like depth so far or a running path sum): pass it <strong>down as a parameter</strong>.</li><li><strong>From the children</strong> (“what’s below me?”, like height or subtree size): <strong>return it up</strong> and combine.</li></ul><h3>Two styles of getting the result out</h3><ol><li><strong>Collector style:</strong> a shared list where every call appends its value. Nothing is returned.</li><li><strong>Return style:</strong> each call <strong>returns</strong> its result, and the parent <strong>aggregates</strong> them. This is the natural fit for <strong>post-order</strong>problems.</li></ol><h3>Danger zone</h3><p>Python’s default recursion limit is about <strong>1,000</strong> calls.</p><ul><li>The call stack holds at most the <strong>longest path</strong> (the tree’s height), not every node.</li><li>A tree of 5,000 nodes where every node is a left child has a height of 5,000.</li><li>Recursing on it raises a RecursionError.</li></ul><p><strong>Fix:</strong> use the <strong>iterative</strong> version, where you manage the stack yourself.</p><p><strong>Check yourself 2:</strong> A function promises “return the sum of all values in the tree.” What should it return for an empty tree (None)?</p><h3>Lesson 3: Recursive DFS (Pre / In / Post)</h3><h3>The finger trick</h3><p>Trace a line around the outside of the tree, starting at the root and going counter-clockwise (down the left side first). As your finger travels, it passes <strong>every node three times</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4668c0f694e5280a5f5d0ca427a97aed/href">https://medium.com/media/4668c0f694e5280a5f5d0ca427a97aed/href</a></iframe><p>To get a traversal, write down each node the moment your finger makes the matching touch. There’s one walk around the tree; the three orders only differ in <strong>which touch you write the node down on</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eqKL3S3EuiXvB5HkA2-uCQ.gif" /></figure><p><em>One walk, three orders. ▼ marks the left-side touch (pre-order), ◆ the touch underneath (in-order), and ▲ the right-side touch (post-order).</em></p><p>Here’s the same walk as code sees it. Watch the call stack on the right: it’s always the path from the root to the current node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Q6pHHkc4IEe_w-GnIJr8rA.gif" /></figure><p><em>Pre-order: each node is recorded the moment its call starts.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*KrExbkCBt-9OTsyI_O8z9g.gif" /></figure><p><em>In-order: each node is recorded after its left side finishes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QAj6L2OLMHpBEjUB8ACB_Q.gif" /></figure><p><em>Post-order: each node is recorded only after both children return.</em></p><h3>The four questions behind the recursive algorithm</h3><p>Answer these in words before you type any code:</p><ol><li><strong>Goal:</strong> Given a node, drop every value in its subtree into the basket in pre-, in-, or post-order.</li><li><strong>Base case:</strong> An empty tree (None) has nothing to add, so simply return.</li><li><strong>Leap of faith:</strong> Trust that the calls on the left and right subtrees each add their own values to the basket correctly.</li><li><strong>My job:</strong> Drop my own value into the basket at the right moment relative to those two calls.</li></ol><blockquote><em>💡 Across pre-, in-, and post-order, </em><strong><em>only the position of step 4 changes</em></strong><em>. Everything else stays the same.</em></blockquote><h3>Template</h3><pre>def dfs(node, basket):<br>    if node is None:              # 2. base case<br>        return<br>    # basket.append(node.val)     # 4. here → pre-order<br>    dfs(node.left, basket)        # 3. trust the left subtree<br>    # basket.append(node.val)     # 4. here → in-order<br>    dfs(node.right, basket)       # 3. trust the right subtree<br>    # basket.append(node.val)     # 4. here → post-order</pre><p>Pick one of the three lines, wrap it in a function that creates the basket and returns it, and you have a traversal.</p><blockquote><em>⚠️ A Python gotcha: if you define </em><em>dfs inside your outer function and only call </em><em>basket.append(...), you don&#39;t need </em><em>nonlocal. Appending changes what&#39;s </em>in<em> the list. You only need </em><em>nonlocal when you </em><strong><em>reassign</em></strong><em> the name, like </em><em>count += 1.</em></blockquote><h3>When to use each traversal</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5838b53570da0acc5d6b69aeedbec0b4/href">https://medium.com/media/5838b53570da0acc5d6b69aeedbec0b4/href</a></iframe><h3>Time and space analysis</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bef635709c7d1df596b1ccdecd1f094/href">https://medium.com/media/9bef635709c7d1df596b1ccdecd1f094/href</a></iframe><p>h depends on the tree&#39;s shape:</p><ul><li><strong>Balanced tree:</strong> h = O(log n). A balanced tree with a million nodes is only about 20 levels deep.</li><li><strong>Skewed tree</strong> (every node has one child): h = O(n).</li></ul><p>This O(h) counts only the call stack. The basket itself holds all n values, which adds O(n) if you count the output.</p><p><strong>Check yourself 3:</strong> Take pre-order and swap the two recursive calls so it goes right before left. What does it output on the example tree?</p><h3>Lesson 4: Iterative DFS</h3><h3>How the recursion call stack maps to your own stack</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2800668903993f42eec1cd8379cd3c45/href">https://medium.com/media/2800668903993f42eec1cd8379cd3c45/href</a></iframe><blockquote><em>⚠️ </em><em>stack.pop() takes from the end. If you ever write </em><em>pop(0), you&#39;re taking from the front. That&#39;s a queue, and you&#39;ve accidentally started writing BFS.</em></blockquote><h3>Pre-order traversal 🟢 Easy</h3><p>Record each node <strong>as soon as you pop it</strong>, then push its children onto the stack.</p><blockquote><em>💡 </em><strong><em>Trick:</em></strong><em> We want </em><strong><em>left</em></strong><em> processed before </em><strong><em>right</em></strong><em>. A stack is LIFO, so whatever goes in last comes out first. Push </em><strong><em>right first, then left</em></strong><em>, so left is on top.</em></blockquote><pre>def preorder(root):<br>    if root is None:<br>        return []<br>    result, stack = [], [root]<br>    while stack:<br>        # 1. pop a node from the top<br>        # 2. record its value<br>        # 3. push its children (right first, then left)<br>        pass<br>    return result</pre><h3>In-order traversal 🟡 Medium</h3><p>We can’t record a parent when we first see it, because its <strong>entire left subtree</strong> has to come first. Think of sliding down a banister and leaving breadcrumbs:</p><ol><li>Keep going <strong>left</strong>, pushing every node onto the stack.</li><li>When you run out of nodes, <strong>pop</strong> the most recent one and <strong>record</strong> it.</li><li>Move to its <strong>right</strong> child and repeat from step 1 (go all the way left in that subtree).</li></ol><h4>Walkthrough</h4><pre>    1<br>   / \<br>  2   3</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9619fb88101f7169d1cafb20f1bc03bc/href">https://medium.com/media/9619fb88101f7169d1cafb20f1bc03bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5_-gU1fQGXFfwV7z1OdY0w.gif" /></figure><p><em>The banister on the full example tree: slide left leaving breadcrumbs, pop and record, then step right.</em></p><pre>def inorder(root):<br>    result, stack = [], []<br>    curr = root<br>    while ___ or ___:        # work can be in two places<br>        # 1. go all the way left, pushing each node<br>        # 2. pop the most recent node and record it<br>        # 3. move to its right subtree<br>        pass<br>    return result</pre><h3>Post-order traversal 🔴 Hard</h3><p>There are two ways to do it.</p><h4>1. The reversal trick (not a true post-order)</h4><p>In iterative pre-order we pushed <strong>right before left</strong>. Flip that and push <strong>left before right</strong>. Popping now gives:</p><pre>me → right → left</pre><p>Reverse the result and you get:</p><pre>left → right → me   ✅ post-order</pre><blockquote><em>⚠️ The output is correct, but nodes aren’t actually </em><strong><em>processed</em></strong><em> in post-order. That matters when a parent needs its children’s results while traversing (height, diameter, balance).</em></blockquote><h4>2. The true way: visited checkmark ✔️</h4><p>Push each node with a <strong>visited</strong> flag:</p><ul><li><strong>First time</strong> you pop it (unchecked): push it back <strong>checked</strong>, then push its children.</li><li><strong>Second time</strong> you pop it (checked): its children are done, so <strong>record</strong> it.</li></ul><pre>def postorder(root):<br>    if root is None:<br>        return []<br>    result, stack = [], [(root, False)]<br>    while stack:<br>        node, visited = stack.pop()<br>        if visited:<br>            # children are done → record me<br>            pass<br>        else:<br>            # push back three things: (node, True), the right child, the left child<br>            # which order makes left pop first, then right, then me?<br>            pass<br>    return result</pre><blockquote><em>💡 Bonus: with the checkmark trick, pre-, in- and post-order are the same code again. Only where </em><em>(node, True)sits among the three pushes changes.</em></blockquote><h3>Time and space complexity</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47225643a3a8c2ac5169b3b01be2e317/href">https://medium.com/media/47225643a3a8c2ac5169b3b01be2e317/href</a></iframe><p><strong>Check yourself 4:</strong> In the banister in-order walk on the example tree, what’s still on the stack at the moment you record your very first value?</p><h3>Lesson 5: BFS (Level Order)</h3><p>BFS is the easiest of them all. We process everything level by level, so we use a queue: the node that entered first gets processed first.</p><p>Picture taking your whole family to the DMV. The clerk calls your grandfather first. While he’s being served, he sends his children to the back of the line. When each of them is served, they send their own children to the back. So the clerk finishes your parents’ entire generation before reaching yours. That’s BFS.</p><p>Compared with iterative pre-order, only two things change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b86ea291912f8bcdf72b6f1c08d0d7a/href">https://medium.com/media/4b86ea291912f8bcdf72b6f1c08d0d7a/href</a></iframe><p><strong>Important:</strong> use collections.deque, not a list. list.pop(0) shifts every remaining element forward, so each pop costs O(n). deque.popleft() costs O(1).</p><h3>The bell trick: knowing where a level ends</h3><p>Many BFS problems need each level separately (level lists, right-side view, minimum depth). At the start of each round, a bell rings: snapshot len(queue). That&#39;s exactly one level. Serve exactly that many nodes; children added during the round wait for the next bell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XPQjVORmdxSWOsEQOVFD9Q.gif" /></figure><p><em>Each bell snapshots the line. The highlighted band is the level being served.</em></p><pre>from collections import deque<br>def level_order(root):<br>    if root is None:<br>        return []<br>    result, q = [], deque([root])<br>    while q:<br>        width = len(q)           # the bell: snapshot this level&#39;s size<br>        for _ in range(width):<br>            # 1. take a node from the front<br>            # 2. record its value<br>            # 3. add its children to the back (left, then right)<br>            pass<br>    return result</pre><h3>Recursive BFS</h3><p>With recursive DFS, the call stack naturally gives us the stack. Nothing gives us a queue, so there’s no natural recursive BFS. Two approaches work:</p><ul><li><strong>A. One level per call.</strong> Pass in a list of every node on the current level. Record them, build the list of the next level (their children, left to right), and call yourself on that list. The base case is the thinnest possible level: an empty list. This is truly BFS-shaped.</li><li><strong>B. DFS in disguise.</strong> Run a normal pre-order DFS, passing the <strong>depth</strong> down as a parameter. Keep one bucket per level and append each node’s value to the bucket at its depth. At the end, join the buckets. This must be <strong>pre-order with left before right</strong>: a parent creates its level’s bucket before any child needs the next one, and each bucket fills left to right.</li></ul><p>Both recurse once per level, so a very deep tree still hits the recursion limit.</p><h3>Time and space complexity</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00117dec5fbe45b5b0b389fcaef0c727/href">https://medium.com/media/00117dec5fbe45b5b0b389fcaef0c727/href</a></iframe><p>On a perfectly balanced tree, the bottom level holds about half of all nodes. So on bushy trees, BFS can use far more memory than DFS.</p><p><strong>Check yourself 5:</strong> What goes wrong if you skip the width = len(q) snapshot and loop with while len(q) &gt; 0 inside each round?</p><h3>Try It Yourself</h3><p>The gist below holds the test harness: one Python file with an empty function for each of the 8 traversals, plus nine test trees to check them against (empty, single node, skewed lines, a zig-zag, an expression tree and a BST) and a 3,000-node deep tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b2faa87669b849cb4d3ffc6934e924b/href">https://medium.com/media/9b2faa87669b849cb4d3ffc6934e924b/href</a></iframe><ul><li><strong>Copy</strong> traversal_harness.py into a file on your computer. All you need is Python 3.</li><li><strong>Fill in a function</strong>, replacing raise NotImplementedError with your code.</li><li><strong>Run</strong> python traversal_harness.py. Functions you haven&#39;t written yet are skipped, so you can go one at a time.</li><li><strong>Read the output:</strong> each failing tree shows the expected and actual order, plus a hint for common mistakes like returning None.</li></ul><p>Stuck? traversal_harness_solved.py in the same gist has a working version of every traversal. Try the template first.</p><p>A suggested order: the three recursive versions first, then iterative pre-order, the in-order banister, post-order (reversal trick first, then the checkmark), and finally both BFS versions. When the deep tree passes for your iterative code, you’ve escaped the recursion limit.</p><h3>Check yourself: answers</h3><ol><li><strong>BFS.</strong> It reaches everything one step away before anything two steps away, so the first 42 it finds is the closest.</li><li><strong>0.</strong> It’s the sum of no numbers, and it keeps the parent’s math working: node.val + 0 + 0.</li><li><strong>[1, 3, 6, 2, 5, 4]</strong>. Reverse it and you get post-order, [4, 5, 2, 6, 3, 1]. That&#39;s the reversal trick from Lesson 4.</li><li><strong>[1, 2]</strong>. You pushed 1, 2 and 4 while sliding left, then popped 4 to record it.</li><li>Children added during the round get served in the same round, so the whole tree lands in one “level”. The flat order is still right, but the level boundaries are gone.</li></ol><h3>Wrapping up</h3><p>Every traversal here is one idea in different clothes: a walk around the tree, plus a container that remembers where to go next. A stack goes deep; a queue goes wide. Recursion lends you a stack for free, at the cost of a depth limit. Once that clicked for me, I stopped memorizing and started deriving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c430ada3186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Runtime Environment; Engine, Event Loop, Queue, and APIs]]></title>
            <link>https://umerxzubairy.medium.com/javascript-behind-the-scenes-part-1-javascript-runtime-environment-engine-event-loop-queue-a52ac0a175a9?source=rss-8e1e400c5544------2</link>
            <guid isPermaLink="false">https://medium.com/p/a52ac0a175a9</guid>
            <category><![CDATA[javascript-engine]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Umer Naeem]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 03:34:52 GMT</pubDate>
            <atom:updated>2023-12-25T01:02:15.200Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://medium.com/@mumer.naeem217/list/javascript-behind-the-scenes-a26c5f02d9af">JavaScript: Behind the Scenes</a></h4><h4>The article explores the fundamentals of JavaScript, including its runtime environment, engine, event loop, queue, and APIs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLSxtDos7Nlavf7A" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Disclaimer: </strong>This series of articles acknowledge Sheldon Marsh’s exceptional JavaScript content in the YouTube playlist <a href="https://youtube.com/playlist?list=PLszEO9SmFAtycVyXqe-a4EEJmowHKCEEW&amp;si=LdLcCesT4tHP_SaU">“Javascript: Behind the Scenes”</a>. I intend to explore and discuss the content further, and I recommend checking out the original playlist. I do not claim ownership of the content but rather pay tribute to Sheldon Marsh’s creativity and effort in curating it. Please support the original creator by liking, sharing, and subscribing to their YouTube channel. Thanks for appreciating the original work.</blockquote><p>Hey there 👋, Have you ever felt like you know something but not completely? That’s how I feel about JavaScript! I recently came across a quote from Kyle Simpson, the author of “You Don’t Know JS” that says</p><blockquote>I don’t think anyone ever really <em>knows</em> JS, not completely anyway.</blockquote><p>It’s true for me, too! I learned JavaScript during my first internship, but unfortunately, the time was so short that I didn’t get a chance to explore the underlying concepts. Although I was always intrigued by how JS worked under the hood, but since it doesn’t require you to understand it fully before using it, I kept procrastinating.</p><p>Finally, after waiting for so long, I decided to take the step and learn the concepts. I started searching for a good resource on JavaScript, but I couldn’t find anything that covered everything. After further searching, I stumbled upon this really nice playlist that helped me clear all my concepts! I was so excited that I decided to write a series of medium articles based on these videos and share them with the community.</p><p>First, let’s try to understand the difference between a JavaScript Engine and a JavaScript Runtime Environment. To understand, let’s start with JE.</p><h3><strong>JavaScript Engine</strong></h3><p>Since JS is an interpreted language, we don’t need to compile it; Instead, it is read line by line and executed directly. Just like any other programming language, we need some kind of program that executes that code. Similarly, a JavaScript Engine is the program that is responsible for the execution of a JavaScript code; It ensures that the code is validated, parsed, and executed properly.</p><p>Every browser has a JE that powers it.</p><ul><li>Google Chrome uses a <a href="https://en.wikipedia.org/wiki/V8_(JavaScript_engine)">v8</a> engine developed by Google.</li><li>Firefox uses the SpiderMonkey engine.</li><li>Safari uses the Nitro engine developed by Apple.</li><li>Microsoft Edge initially used Chakra, but later, they started using v8.</li></ul><p>We have different components of the JavaScript Engine, like Call Stack, Heap, and Garbage Collector, that help with memory allocation and deallocation during the execution of a program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5Ak9FTGGLqQFAc53U_i_g.png" /><figcaption>A Visualization of JavaScript Engine</figcaption></figure><h4><strong>Call Stack</strong></h4><p>A call stack is used to keep track of the current execution context. An execution context contains all the items needed to complete the execution. There are two kinds of execution context.</p><ol><li><strong>Global Execution Context</strong>: This is the default execution context created when the script starts executing. Each program can only have one Global Execution Context.</li><li><strong>Function Execution Context</strong>: Whenever a function is invoked, a new function execution context for that function is created, therefore we can have multiple Function Execution Context</li></ol><p>The call stack operated on the LIFO (Last In, First Out) principle. By observing a call stack, we can tell which function is executing right now along with its variables and a history of all functions that led to the invocation of this function.</p><p>When a function starts executing, it is pushed into a stack, kind of like a stack of dishes. And just like how you add more dishes on top of each other, if another function is invoked while the first one is still being executed, it is also pushed into the stack. Once the second function is done executing, it gets popped off the stack, and the first function resumes where it left off. This process keeps happening recursively for all the functions that are called.</p><p>If you’re interested in learning about call stacks. Check out the video below — it shows the call stack in action. And if you want to give it a try yourself, I’ve also attached the code for you to test out on your local browser. Have fun exploring!</p><blockquote>Note: anonymous means the function is in a global execution context.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP7a3X2fb3MI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP7a3X2fb3MI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP7a3X2fb3MI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e43e3a7a5ea9c23bb597ff692423b5e/href">https://medium.com/media/5e43e3a7a5ea9c23bb597ff692423b5e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f43a69e680ea9ba285ea05c77cb33f88/href">https://medium.com/media/f43a69e680ea9ba285ea05c77cb33f88/href</a></iframe><h4>Heap</h4><p>Heap memory is an unstructured pool of memory used to allocate dynamic memory for objects and functions. After the memory is not in use, the Garbage Collector deallocates that memory. A point to be noted here is that not all data is stored in the heap. The data with a fixed data size, like primitive data types, are stored in the call stack along with the execution context, whereas the data that doesn’t have a fixed size is stored in the Heap. In other words, the stack and the heap work together to provide a smooth memory allocation process.</p><p>Watch the video below to see the heap in action. I have also attached the code below to test it on your local browser.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEO9hjYNuQ9o&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEO9hjYNuQ9o&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FEO9hjYNuQ9o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc927f78ec8fedbee8352e9adc27f4a/href">https://medium.com/media/6fc927f78ec8fedbee8352e9adc27f4a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4e3161ed5f18d0d17f93d8732ccf23/href">https://medium.com/media/aa4e3161ed5f18d0d17f93d8732ccf23/href</a></iframe><h3>JavaScript Runtime Environment</h3><p>Have you ever executed a very large loop at the click of a button? Let’s see what happens.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWBqkv74I6Rs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWBqkv74I6Rs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWBqkv74I6Rs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b7ffd495b1b72024fbd3c579353b496/href">https://medium.com/media/1b7ffd495b1b72024fbd3c579353b496/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9b6f1c13dc71208d4144b9281741617/href">https://medium.com/media/e9b6f1c13dc71208d4144b9281741617/href</a></iframe><p>Observe the button; when we click it, it stays pressed until the execution is complete. This is happening due to the fact that JS is a synchronous single-threaded language having a single call stack. A single-call stack means it can only do one thing at a time. This way, our users can’t get a smooth experience because we have long tasks like performing AJAX calls, DOM manipulation, etc.</p><p>Gladly, we have a concurrency model in JS provided by the JavaScript Runtime Environment. To understand this concurrency model, observe the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRMtDK-c7Eb3jU9SODoI7A.png" /><figcaption>A Visualization of Concurrency Model in JavaScript</figcaption></figure><h4>Web APIs</h4><p>JavaScript Runtime Environment provides us with a wide range of Web APIs for the task that may be blocking the thread otherwise. Various tasks can be handled using Web APIs, including but not limited to DOM manipulation, HTTP Requests, and Event Handlers. Whenever we execute a function and approach such Web APIs, the function invokes them and continues its execution. Once these Web APIs have a callback ready, they push it into the Callback Queue.</p><h4>Callback Queue</h4><p>A callback queue operates on the FIFO (First In, First Out) principle. This queue keeps storing the callbacks from the Web APIs in the order it gets them. These callbacks sit in the queue until the event loop takes them out of the queue.</p><h4><strong>Event Loop</strong></h4><p>The event loop is a loop which is checking the call stack. It will take the element from the queue and push it into the call stack if it is empty. A point to note here is that even if the callback is ready and the previous execution of the function that triggered the callback has not been completed, the callback will not be pushed into the call stack.</p><p>This event loop is the reason why JavaScript, being a synchronous language, can still give us the ability to perform concurrent tasks, as it keeps pushing the callbacks once the call stack becomes empty.</p><p>Now that you know that the event loop only pushes the callback once the call stack is empty. Let’s see a demonstration and proof that the event loop exists.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3ODTr8MoXGs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3ODTr8MoXGs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3ODTr8MoXGs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf2340dfe7407fe37e312fa445ab51f9/href">https://medium.com/media/cf2340dfe7407fe37e312fa445ab51f9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046a99de8dcf757dc4e30577f2a4bc45/href">https://medium.com/media/046a99de8dcf757dc4e30577f2a4bc45/href</a></iframe><blockquote>A point to note over here is that the callback always executes in the global execution context.</blockquote><p>Thank you very much for taking the time to read this article. Let me know what you think about the article in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a52ac0a175a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>