<?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 Ugochukwu Gospel on Medium]]></title>
        <description><![CDATA[Stories by Ugochukwu Gospel on Medium]]></description>
        <link>https://medium.com/@ugochukwugospeli111?source=rss-548d21ba4912------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P0n87eVtlbajlbpIjqRacw.jpeg</url>
            <title>Stories by Ugochukwu Gospel on Medium</title>
            <link>https://medium.com/@ugochukwugospeli111?source=rss-548d21ba4912------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 31 May 2026 22:19:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ugochukwugospeli111/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 The Event Loop]]></title>
            <link>https://medium.com/@ugochukwugospeli111/understanding-the-event-loop-3b7c5f2f2542?source=rss-548d21ba4912------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b7c5f2f2542</guid>
            <dc:creator><![CDATA[Ugochukwu Gospel]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 11:27:24 GMT</pubDate>
            <atom:updated>2024-04-19T13:14:00.677Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ll start this article off by saying that <em>javascript </em>is single-threaded, meaning that your code is executed in a single thread called the callstack.</p><p>But if javascript is really single-threaded, then how does it achieve asynchronous programming?</p><p>Just for context, asynchronous tasks enable JavaScript to execute multiple tasks simultaneously. This capability is achieved in languages such as C++ and Java using a concept known as multi-threading.</p><p>Well, javascript is really single-threaded, however, it achieves it’s asynchronous behavior by using some set of tools that form a system, and the event loop, while being the core is only a single part of these set of tools.</p><p>”What are these tools?” You might ask? Here they are</p><p>1. The call stack</p><p>2. The web apis / nodejs runtime</p><p>3. The task queue and the micro task queue</p><p>4. The event loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwC6sdAy4fsPqtQ5Jmp8Rg.jpeg" /><figcaption>Image of how the event loop works.</figcaption></figure><p>Now let’s look at each piece and understand how they work.</p><ol><li><strong>The Call Stack:</strong> The call stack is a data structure that enables javascript to keep track of function calls. When a function is called, it’s execution context is pushed onto the callstack and when the function is done running, it’s execution context is popped off the stack. An execution context is just an environment a piece of code would run in and it holds all the necessary information for that code to work.</li></ol><p>Consider this piece of code</p><pre>const third = () =&gt; {<br>console.log(&quot;third&quot;);<br>}<br><br>const second = () =&gt; {<br>third();<br>console.log(&quot;second&quot;);<br>}<br><br>const first = () =&gt; {<br>second();<br>console.log(&quot;first&quot;);<br>}<br><br>first();</pre><p>When this code runs, the execution context for <strong><em>first()</em></strong> is pushed onto the stack, which starts running.</p><p>Now it hits <strong><em>second()</em></strong> which is inside <strong><em>first() </em></strong>and pushes it’s execution context onto the stack as well, the same thing happens and pushes the execution context for <strong><em>third()</em></strong> onto the stack.</p><p>Now when <strong><em>third()</em></strong> starts running, the <strong><em>console.log</em></strong> is pushed to the stack which gets executed immediately (i.e logs “first” to the console) and then popped off the stack, since there is no other code in <strong><em>third()</em></strong>, it’s execution context is popped off the stack as well and the control returns back to <strong><em>second()</em></strong>.</p><p>Now in <strong><em>second()</em></strong>, the next line of code is pushed onto the stack and executed which logs “second” to the console and then popped off the stack then the control returns to first(), which executes the <strong><em>console.log(“first”)</em></strong>, pops it off the stack and then pops the function <strong><em>first()</em></strong> off the stack as well.</p><p>This is just an overview of how the stack works.</p><p>2.<strong> The Web APIs / NodeJs Runtime:</strong> When callback based functions or async functions like setTimeOut or http requests are pushed onto the call stack, they are handed off to the web apis (in case the javascript code is run on the brower) or nodejs runtime (in case the javascript code is run outside the browser) instead of blocking the callstack.</p><p>When the asynchronous operation is completed, the callback is pushed to the task queue or in case of async functions, the code after the await line is pushed to the microtask queue.</p><p>3. <strong>The Task Queue and The Microtask Queue:</strong> The task queue and the microtask queue holds the functions that are scheduled to be pushed onto the callstack by the web apis / nodejs runtime when the callstack is empty.</p><p>Just as a side note, the event loop prioritizes the microtask queue over the task queue as when the callstack is empty, it starts by pushing every scheduled function in the microtask queue before it moves onto the task queue.</p><p>4. <strong>The Event Loop:</strong> The event loop is the crucial part that coordinates how execution contexts are pushed onto the stack. Whenever the stack is empty, the event loop first checks the microtask queue and if there are any scheduled functions there, it pushes it’s execution context to the stack and continues doing so until it empties the microtask queue before moving onto the task queue.</p><p>Using this approach, javascript is able to achieve an asynchronous behavior using just a single thread.</p><p>I hope this article was of some help to you in understanding the event loop and how javascript achieves it’s asynchronous behavior.</p><p>So next time you’re writing code for your server or web, you’ll now be able to make informed decisions on the approach to take inorder to make your code faster by not blocking the event loop with heavy code.</p><p>My Socials:</p><ul><li><a href="https://youtube.com/@Gospel011"><strong>YouTube</strong></a></li><li><a href="https://linkedin.com/in/ugochukwu-gospel"><strong>LinkedIn</strong></a></li><li><a href="https://twitter.com/_Gospel011"><strong>Twitter</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b7c5f2f2542" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Showdown: .forEach vs. .map – Unraveling the Key Differences]]></title>
            <link>https://medium.com/@ugochukwugospeli111/javascript-showdown-foreach-vs-map-unraveling-the-key-differences-2e212698714b?source=rss-548d21ba4912------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e212698714b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ugochukwu Gospel]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 11:34:06 GMT</pubDate>
            <atom:updated>2023-09-24T18:22:44.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Showdown: .forEach vs. .map – Unraveling the Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*y48cWNpBDWr-E-h7w1p5KA.png" /><figcaption>From watchmojo.com</figcaption></figure><p><strong>Introduction:</strong><br>JavaScript, the versatile language that powers the web, offers developers an array of tools to manipulate data and iterate through arrays. Two of the most commonly used methods, <strong>`.forEach`</strong> and <strong>`.map`</strong>, might seem similar at first glance, but beneath the surface, they have distinct purposes and behaviors.</p><p>When I was starting as a NodeJs backend developer, I watched tutorials online where the tutor used these two methods a lot when working with arrays, so much so that I started asking myself the difference between them and when to use each one. This is what I’ll explain in detail in this article so that even beginners would understand.</p><p>So now let’s go on a journey through the JavaScript jungle as we explore the exciting differences between these two powerful array methods :).</p><p>Here are the points we’ll be focusing on:<br>1.	The purpose with examples<br>2.	Return values with examples<br>3.	Use cases with examples<br>4.	Immutability<br>5.	Method chaining with examples</p><p>1.<strong> The Purpose:</strong><br>• <strong>`.forEach`</strong>: This method is like the trusty tour guide of JavaScript. It takes you through each item in an array and allows you to perform actions on each element without changing the original array. It’s like a friendly stroll through a shop’s catalog where you can admire the things listed on them without altering them.</p><p>As an example, let’s write code to admire a shop’s drinks catalog:</p><pre>const drinksCatalog = [<br>  { drink: ‘Coffee’, price: 3.50 },<br>  { drink: ‘Tea’, price: 2.99 },<br>  { drink: ‘Soda’, price: 3.75 },<br>  { drink: ‘Lemonade’, price: 5.99 },<br>  { drink: ‘Smoothie’, price: 2.85 }<br>];<br><br>drinksCatalog.forEach(el =&gt; {<br>    if (el.price &lt; 3) {<br>        console.log(`So cheap?! Are you sure this is a ${el.drink}?\n`)<br>    }<br>    else if (el.price &lt; 4) {<br>        console.log(`Hmm… This one’s o…k? But I don’t take cheap ${el.drink}s…sigh\n`)<br>    }<br>    else {<br>        console.log(`How can a ${el.drink} be soo expensive??\n`)<br>         }<br>})<br></pre><p>Expected output:</p><pre>Hmm… This one’s o…k? But I don’t take cheap Coffees…sigh<br><br>So cheap?! Are you sure this is a Tea?<br><br>Hmm… This one’s o…k? But I don’t take cheap Sodas…sigh<br><br>How can a Lemonade be soo expensive??<br><br>So cheap?! Are you sure this is a Smoothie?<br><br></pre><p>• <strong>`.map`:</strong> Think of `.map` as the shop’s catalog from which you can create a brand new catalog by applying a function to each element of the original one. It’s like wanting to purchase atleast one of everything in a shop, so you get the shop’s catalog and then create a new one where you’ve specified the quantity of each item you want to purchase.</p><p>Let’s actually write the code for that:</p><pre>// This is a function that generates a random integer between 0 and 10.<br>// I’ll use it to generate random values for the quantity field.<br>const randInt = () =&gt; {<br>    return Math.floor(Math.random() * 10)<br>}<br><br>const drinksCatalog = [<br>  { drink: ‘Coffee’, price: 3.50 },<br>  { drink: ‘Tea’, price: 2.99 },<br>  { drink: ‘Soda’, price: 3.75 },<br>  { drink: ‘Lemonade’, price: 5.99 },<br>  { drink: ‘Smoothie’, price: 2.85 }<br>];<br><br>const orderCatalog = drinksCatalog.map(el =&gt; {<br>    const item = el;<br>    item.quantity = randInt()<br>    return item<br>})<br>console.log(orderCatalog);<br></pre><p>Expected output:</p><pre>[<br>  { drink: ‘Coffee’, price: 3.50, quantity: 3 },<br>  { drink: ‘Tea’, price: 2.99, quantity: 5 },<br>  { drink: ‘Soda’, price: 3.75, quantity: 2 },<br>  { drink: ‘Lemonade’, price: 5.99, quantity: 4 },<br>  { drink: ‘Smoothie’, price: 2.85, quantity: 1 }<br>]<br></pre><p>2. <strong>Return Values:</strong><br>• <strong>`.forEach`:</strong> It returns `undefined`. That’s right, it’s all about side effects – performing actions rather than producing results directly. That’s why we did not store it in a variable. Let’s actually do it and then see the output.</p><pre>const drinksCatalog = [<br>  { drink: ‘Coffee’, price: 3.50, quantity: 3 },<br>  { drink: ‘Tea’, price: 2.99, quantity: 5 },<br>  { drink: ‘Soda’, price: 3.75, quantity: 2 },<br>  { drink: ‘Lemonade’, price: 5.99, quantity: 4 },<br>  { drink: ‘Smoothie’, price: 2.85, quantity: 1 }<br>]<br><br>const admireCatalog = drinksCatalog.forEach(el =&gt; {<br>    if (el.price &lt; 3) {<br>        console.log(`So cheap?! Are you sure this is a ${el.drink}\n`)<br>    }<br>    else if (el.price &lt; 4) {<br>        console.log(`Hmm… This one’s o…k? But I don’t take cheap ${el.drink}s…sigh\n`)<br>    }<br>    else {<br>        console.log(`How can a ${el.drink} be soo expensive??\n`)<br>         }<br>})<br>console.log(admireCatalog)<br></pre><p>Expected output:</p><pre>undefined<br></pre><p>• <strong>`.map`:</strong> This method is the producer. It returns a new array filled with the results of applying the provided function to each element of the original array. Take the code for `.map` in section 1 for example, we were able to store the result of the `.map` operation in a variable (orderCatalog) and then log that variable to the console which outputs the new array. This is possible because the variable holds the return value of the `.map` operation which as we can see, is an array.</p><pre>[<br>  { drink: ‘Coffee’, price: 3.50, quantity: 3 },<br>  { drink: ‘Tea’, price: 2.99, quantity: 5 },<br>  { drink: ‘Soda’, price: 3.75, quantity: 2 },<br>  { drink: ‘Lemonade’, price: 5.99, quantity: 4 },<br>  { drink: ‘Smoothie’, price: 2.85, quantity: 1 }<br>]<br></pre><p>3. <strong>Use Cases:</strong><br>• <strong>`.forEach`:</strong> Perfect for scenarios where you need to loop through an array and perform an action on each element, like logging data to the console for example or updating the DOM.</p><p>Infact, apart from logging stuff to the console, we can also use `.forEach` to create a new array (*would explain in a second) that may or may not be of the same length as the original one. For example, imagine we want to extract all the even numbers from one array into a new array, the code can look like this</p><pre>// This numbersArray contains ten numbers with four of them (6, 8, 12 and 10) being even.<br>//Our goal is to extract these four numbers.<br><br>const numbersArray = [6, 15, 8, 21, 12, 19, 10, 27, 17, 33];<br><br>let evenArray = [];<br><br>numbersArray.forEach(el =&gt; {<br>    if (el % 2 === 0) evenArray.push(el)<br>})<br><br>console.log(evenArray)<br></pre><p>Expected output:</p><pre>[6, 8, 12, 10]<br></pre><p>As you can see, the length of the original numbersArray is 10 while that of the new evenArray is 4. This is not possible with `.map` as the new array must be of the same length with the original one. It can even go as far as returning undefined to elements that don’t have a value. For example</p><pre>const numbersArray = [6, 15, 8, 21, 12, 19, 10, 27, 17, 33];<br><br>const evenArray = numbersArray.map(el =&gt; {<br>    If (el % 2 === 0) return el<br>})<br><br>console.log(evenArray)<br></pre><p>Expected output:</p><pre>[6, undefined, 8, undefined, 12, undefined, 10, undefined, undefined, undefined]<br></pre><p>See? The length of the array remained unchanged and the `.map` operation returned undefined for numbers that are not even.</p><p>*<strong>PLEASE NOTE:</strong> While `.forEach` doesn’t return a new array, we can always declare a separate variable containing an empty array and then instead of logging to the console, we can conditionally push items into the empty array which is what we did in the example above.</p><p>• <strong>`.map`</strong>: Ideal when you want to transform an array into something new, like doubling each number in an array or converting a list of names into uppercase.</p><p>As an example, let’s write code to increment our employees salaries by $10,000</p><pre>const employeeSalaries = [<br>  [“John”, 50000],<br>  [“Alice”, 60000],<br>  [“Bob”, 55000],<br>  [“Eva”, 62000],<br>];<br><br>const newEmployeeSalaries = employeeSalaries.map(el =&gt; {<br>    const employee = el<br>    employee[1] += 10000<br>    return employee<br>})<br><br>console.log(newEmployeeSalaries)<br><br></pre><p>Expected output:</p><pre>[<br>  [“John”, 60000],<br>  [“Alice”, 70000],<br>  [“Bob”, 65000],<br>  [“Eva”, 72000],<br>];<br></pre><p>4. <strong>Immutability:</strong><br>• <strong>`.forEach`:</strong> It doesn’t create a new array, so the original one remains unchanged. That’s also why it returns undefined</p><p>• <strong>`.map`:</strong> This method is all about immutability. It preserves the original array and creates a fresh one with the transformed data. Just like the `.map` part in section 1 above, it is that new array that we stored in the orderCatalog variable.</p><p>5. <strong>Chaining:</strong><br>• <strong>`.forEach`:</strong> You can’t chain additional array methods after a `.forEach` loop, as it doesn’t return an array, so trying to attach an array method to it would result in an error.</p><p>• <strong>`.map`:</strong> Being the team player it is, `.map` returns a new array, making it chainable with other array methods, just like how a shop attendant can perform further actions on that new catalog you created in section 1, like calculating the total price of each item based on the quantity you ordered.</p><p>To do that in code, let’s attach another .map method to the order catalog and then calculate the price of each order.</p><pre>const drinksCatalog = [<br>  { drink: ‘Coffee’, price: 3.50 },<br>  { drink: ‘Tea’, price: 2.99 },<br>  { drink: ‘Soda’, price: 3.75 },<br>  { drink: ‘Lemonade’, price: 5.99 },<br>  { drink: ‘Smoothie’, price: 2.85 }<br>];<br><br>const orderCatalog = drinksCatalog.map(el =&gt; {<br>    const item = el;<br>    item.quantity = randInt();<br>    return item;<br>})<br><br>const orderPriceDetail = orderCatalog.map(el =&gt; {<br>    const order = el;<br>    order.orderPrice = order.price * order.quantity;<br>    return order;<br>})<br><br>console.log(orderPriceDetail)<br></pre><p>Expected output:</p><pre>[<br>  { drink: ‘Coffee’, price: 3.50, quantity: 3, orderPrice: 10.50 },<br>  { drink: ‘Tea’, price: 2.99, quantity: 5, orderPrice: 14.95 },<br>  { drink: ‘Soda’, price: 3.75, quantity: 2, orderPrice: 7.50 },<br>  { drink: ‘Lemonade’, price: 5.99, quantity: 4, orderPrice: 23.96 },<br>  { drink: ‘Smoothie’, price: 2.85, quantity: 1, orderPrice: 2.85 }<br>]<br></pre><p><strong>Final thoughts…:</strong><br>In the grand JavaScript arena, `.forEach` and `.map` are both valuable players, each with its own distinct role. `.forEach` is your trusted guide for touring and admiring adventures, while `.map` is the creative artist who crafts entirely new arrays. Understanding their differences empowers you to wield them effectively in your coding endeavors, making you a JavaScript maestro in your own right.</p><p>So, whether you’re touring a shop’s catalog just for the fun of it or buying out the entire shop, remember that in the world of JavaScript, `.forEach` and `.map` are your reliable companions, each with its own unique charm.</p><p>Happy coding 😊!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e212698714b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>