<?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 Chukwudi Ngwobia on Medium]]></title>
        <description><![CDATA[Stories by Chukwudi Ngwobia on Medium]]></description>
        <link>https://medium.com/@ngwobiachukwudi?source=rss-a0c7eb332492------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*b8MLc6CQbigAnCuyCEmrXQ.jpeg</url>
            <title>Stories by Chukwudi Ngwobia on Medium</title>
            <link>https://medium.com/@ngwobiachukwudi?source=rss-a0c7eb332492------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:11:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngwobiachukwudi/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[Introduction to JavaScript debugging.]]></title>
            <link>https://medium.com/swlh/introduction-to-javascript-debugging-272961b88847?source=rss-a0c7eb332492------2</link>
            <guid isPermaLink="false">https://medium.com/p/272961b88847</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[debbuging]]></category>
            <category><![CDATA[debugger]]></category>
            <category><![CDATA[chrome-dev-tools]]></category>
            <dc:creator><![CDATA[Chukwudi Ngwobia]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 11:46:51 GMT</pubDate>
            <atom:updated>2021-09-12T11:46:51.793Z</atom:updated>
            <content:encoded><![CDATA[<h3>introduction to JavaScript debugging.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf5o8Q4VNY5xjwf0pn178A.jpeg" /><figcaption>source: <a href="https://geekflare.com/http-client-tools/">https://geekflare.com/http-client-tools/</a></figcaption></figure><h3>Introduction</h3><p>New JavaScript devs (and even some advanced devs) often shy away from using debuggers. Usually, it is enough to log values to the console using console.log to view the values we are interested in. While this gets the job done, it is a very limited option to aid debugging during development. And it gets more complex when we’re working with a large codebase with multiple modules. Another reason why using the debugger is not the first option an average JavaScript developer will turn to is because of the amount of work required to set up a simple environment for debugging especially when developing server-side applications (usually with nodeJS).</p><p>In this tutorial, we will look at debugging client-side javascript using the chrome debugger and in a later tutorial, we will look at how to get the same level of convenience on the server-side.</p><h3>Setting up the environment</h3><p>To follow through with this tutorial, you will need a browser (Google chrome, firefox, etc) and a simple web project. I have set up a simple <a href="https://github.com/chuxmykel/client_side_js_debugging">git repo</a> and you can clone it using the command:<br><em>git clone </em><a href="https://github.com/chuxmykel/client_side_js_debugging.git"><em>https://github.com/chuxmykel/client_side_js_debugging.git</em></a><em>.</em></p><p>This project was created using <a href="https://vitejs.dev/guide/#overview">vite</a> but you can apply the concepts learned here to apps built with any JavaScript framework or library as well as vanilla JavaScript.</p><h3>Getting started</h3><p>Once you have cloned the repo, cd into the directory by using the command cd client_side_js_debugging. Next run npm install or yarn install depending on your preferred package manager. Then start the development server by using the command npm run dev or yarn dev.</p><h3>About the app</h3><p>The app is a simple app that has a value displayed between two buttons. The button on the left decrements the value by one and the button on the right does the opposite. (Or they should 😉). If you click any of the buttons, you’ll notice that the value stays the same. Now we have a bug and this article aims to find and solve this bug like a pro 😁.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfN6y9vfc3NOv4CsfHLyiw.png" /><figcaption>The app.</figcaption></figure><h3>The code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81d34b186365840d35088f02907e575/href">https://medium.com/media/d81d34b186365840d35088f02907e575/href</a></iframe><p>At first sight, this looks like it should work right? Unfortunately, it doesn’t. And this article aims to trace and fix the issue with the help of the debugger provided by the dev tools of your browser.</p><h3>Fishing out the issue</h3><p>To trace the issue, we can simply place a bunch of console.log statements to see where the issue is coming from. I.e:</p><pre>...<br>const setState = (newState) =&gt; {<br>  state = {<br>    ...state,<br>    ...newState,<br>  };<br>  console.log(state); // 1st console.log statement<br>  renderNewValue(state);<br>}</pre><pre>const increment = () =&gt; {<br>  const newValue = state.displayValue++;<br>  console.log(newValue); // 2nd console.log statement<br>  setState({ displayValue: newValue });<br>}</pre><pre>const decrement = () =&gt; {<br>  const newValue = state.displayValue++;<br>  console.log(newValue); // 3rd console.log statement<br>  setState({ displayValue: newValue });<br>}<br>...</pre><p>Usually, as a JavaScript developer, the first thing that comes to mind is to think about the functionality of our app and place console.log statements at the places where we think are responsible for the bug and in this case, we place them in the setState , increment and decrement functions. This may not seem like a big issue until we are debugging a large app with functions coming from a lot of external modules.</p><h3>A better approach</h3><p>To debug this app more efficiently and without having to modify our code, we can use the debugger provided by our browser.</p><p>If you use Google Chrome, you can access the developer tools using F12. Then navigate to the sources tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siXEw8fBHfHpFiIS6rlvrQ.png" /><figcaption>chrome dev tools (sources) tab.</figcaption></figure><p>The chrome dev tool shows us some really useful keyboard shortcuts and we can take advantage of them to improve the developer Quality of Life. But in this tutorial, we will navigate our files using the file explorer on the left-hand side of the screen.</p><p>If you take a look at the js folder, you’ll notice your JavaScript files and you can click on the main.js file to see your code displayed on the main screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbh-X807DWOm-l83WnG5mQ.png" /><figcaption>The main.js file open in the chrome debugger.</figcaption></figure><h3>Debugging the application</h3><p>Remember how we placed console.log statements in the code earlier? With the debugger, we don’t need to use log statements. We can simply place breakpoints in our code by clicking a line number on our file as displayed on the debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyuRN5JWaSyw5_F7eCJTTA.png" /><figcaption>The main.js file with breakpoints rather than console.log statements</figcaption></figure><h4>Breakpoints</h4><p>A breakpoint is a point in your code where execution pauses. At each breakpoint, you can inspect variables in the current scope by hovering over a variable.</p><p>To try this out, click one of the buttons in the app (+ or -) and you will notice that the code runs up till the point where you set the breakpoint.</p><p>Let’s try this by clicking the + button. Notice that the code executes up until the point we placed our breakpoint and the line with the breakpoint is highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aZtVE3TD-muhO0y3RO9ig.png" /><figcaption>The main.js file showing a highlighted breakpoint.</figcaption></figure><p>At this point, we can inspect each variable in the current scope. Take a look at the panel on the right-hand side and notice the debugger gives us a bunch of useful information grouped by panels. Some of the panels are the watch, breakpoints, scope, local, module, global etc.</p><h4>Navigating code in the debugger</h4><p>We can move through our code in the debugger using the control buttons on the top right-hand side of the debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*WAD0QmqEkaCSUr_izKkJTg.png" /><figcaption>Buttons for navigating the debugger.</figcaption></figure><p>For more information on what you can achieve with these buttons, take a look at <a href="https://developer.chrome.com/docs/devtools/javascript/reference/">this information</a> provided by Chrome.</p><h3>Fixing our issue</h3><p>Once we click the + button, we see that our code pauses on line 25. We can use the “step over” button to move to the next line of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/1*vDwLPUtjddZIvTN6H3PLKw.png" /><figcaption>The (step over) button.</figcaption></figure><blockquote>If the current line is a function call, the step over button jumps over the function call (allowing the function to execute without inspecting it) to the next line of code.</blockquote><p>Now we can inspect the newValue variable by hovering over it and this shows us the current value. Our bug becomes apparent as we expect this value to be incremented by 1. Clicking the step over button again takes us to our next breakpoint which is in the setState function. And again, we can see that the function is called with { displayValue: 0} as opposed to our expected value {displayValue: 1 }.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VznOolSuKWZ4PEWbgYIdQ.png" /><figcaption>Hovering over the “newValue” variable shows that it’s currently 0.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hnE8bzm9-UExkHwBdDIVA.png" /><figcaption>Hovering over the “newState” argument also shows that it’s set to { displayValue: 0 }.</figcaption></figure><p>To fix this bug, we simply have to modify line 25 of our code to:</p><p>const newValue = ++state.displayValue;</p><p>The same applies to line 30.</p><h3>Conclusion</h3><p>This is an oversimplified example aimed at showing basic debugging with the chrome developer tools. The same concept applies to the dev tools provided in other browsers such as Firefox, Edge and other major browsers. To learn more about the dev tools, you can take a look at <a href="https://developer.chrome.com/docs/devtools/overview/">this link</a>. Take note that whatever knowledge you get from this article and also <a href="https://developer.chrome.com/docs/devtools/overview/">the shared link</a>, is transferrable to any other browser with a few minor differences. Using the debugger can save you a lot of time and make you more productive as a developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=272961b88847" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/introduction-to-javascript-debugging-272961b88847">Introduction to JavaScript debugging.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous JavaScript.]]></title>
            <link>https://levelup.gitconnected.com/asynchronous-javascript-6d219b6eb8ff?source=rss-a0c7eb332492------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d219b6eb8ff</guid>
            <category><![CDATA[javascript-promise]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[callback-hell]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[call-stack]]></category>
            <dc:creator><![CDATA[Chukwudi Ngwobia]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 18:17:56 GMT</pubDate>
            <atom:updated>2020-04-05T20:43:27.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>Asynchronous JavaScript</h3><h4>Not so single-threaded.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qb42wZjU6ImP-xDBS8BfoQ.jpeg" /><figcaption>Single-threaded? Photo by <a href="https://unsplash.com/@amir_v_ali?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">amirali mirhashemian</a> on <a href="https://unsplash.com/s/photos/thread?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>As a JavaScript developer, you probably have read or heard that JavaScript is a single-threaded language. Also, I’m pretty sure a lot of JavaScript developers just “<em>believe</em>” and never question the term or concept and have written thousands of lines of <a href="https://stackoverflow.com/questions/34680985/what-is-the-difference-between-asynchronous-programming-and-multithreading/34681101"><strong><em>asynchronous (multithreaded-ish)</em></strong></a> code without even understanding how it works (don’t feel ashamed😅, you are not alone).</p><h4>What is a thread?</h4><p>According to <a href="https://simple.wikipedia.org/wiki/Thread_(computer_science)">Wikipedia</a>, a <strong>thread</strong> in <a href="https://simple.wikipedia.org/wiki/Computer_science">computer science</a> is short for a <em>thread of execution</em>. Threads are a way for a <a href="https://simple.wikipedia.org/wiki/Computer_program">program</a> to divide (termed <em>“split”</em>) itself into two or more simultaneously (or pseudo-simultaneously) running <a href="https://simple.wikipedia.org/wiki/Task_(computers)">tasks</a>.</p><p>From the definition above, we’re simply saying JavaScript can run only one task at a time <strong><em>right?</em></strong> Well, let’s dig in a little deeper.</p><p>To understand how JavaScript handles tasks, we need to understand the JavaScript call stack.</p><p>The JavaScript call stack is a literal <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)"><strong><em>stack data type</em></strong></a><strong><em> </em></strong>and it stacks each successive function call on the other and pops off the function when its execution has completed. Below is a visual representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wudWlmUNTEGOfmaYDUXSAA.gif" /><figcaption>JavaScript call stack demo. <a href="https://gist.github.com/chuxmykel/81e2c490b1346250a12d643175476c40">Source file</a></figcaption></figure><p>Observe the menu on the right-hand side and focus on the “Call Stack” menu item. Notice how each function call sits on top of the other and gets popped off after its execution completes. But <strong><em>foo</em></strong> was the first function call, right? Why then do we have <strong><em>(anonymous)</em></strong> below foo? This is the main function that runs when we invoke the script, and when this function runs, it encounters three function declarations and one function call <strong><em>(foo)</em></strong> in the global scope. This immediately adds foo to the top of the stack. Now we’re in the block scope of <em>foo</em> and we encounter another function call <strong><em>(console.log()).</em></strong></p><blockquote>Just in case you’re wondering why <strong>console.log()</strong> didn’t show up on the call stack, the JavaScript engine is pretty fast and I was only able to get this visualized because of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger"><strong><em>debugger</em></strong></a><strong><em> </em></strong>statement. And since I can’t put one in the <strong><em>console.log()</em> </strong>function, it pops off immediately it executes.</blockquote><p>After the <strong><em>console.log()</em></strong> is popped off, we encounter another function call <strong><em>(bar())</em></strong> which takes the execution context into the new function and adds the new function on top of the call stack. The <strong><em>foo()</em></strong> function hasn’t left the stack because its execution hasn’t completed so now we have <strong><em>anonymous(), foo()</em></strong> and <strong><em>bar()</em></strong> on the stack. The process is the same for the execution of the <strong><em>bar()</em></strong> function and it puts <strong><em>baz()</em></strong> on top of the call stack. <strong><em>baz() </em></strong>puts <strong><em>console.log()</em></strong> on the stack, pops it off and puts it once again with the farewell message and then pops it off, pops off the <strong>baz()</strong> function and then returns to <strong><em>bar()’s</em></strong> execution context runs the second <strong><em>console.log()</em></strong> and pops it off the stack, pops <strong>bar()</strong> off the stack and the same process for <strong><em>foo()</em></strong>.</p><p>I’m almost certain my words have failed to convey this concept clearly so I took the liberty of creating a gif to help visualize the entire process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*VnPa2qxPZkEfQte5w0qUqQ.gif" /><figcaption>Visualizing our code’s execution against the call stack</figcaption></figure><p>Now you should be able to see how <em>console.log()</em> fits into the process clearly and also how every line of code is executed.</p><p>This is how JavaScript runs <a href="https://gist.github.com/chuxmykel/21c6e5044b0cfdc2c60fa1873a836dc4"><strong><em>Synchronous</em></strong></a> code. All functions run to completion and are popped off the stack when they have nothing else to do.</p><p>If we have built a mental model around the way the JavaScript engine executes code using the <strong><em>call stack</em></strong>, we can already begin to question how it can execute multiple tasks simultaneously(or somewhat simultaneously) with just one call stack.</p><h4>Asynchronous JavaScript</h4><p>Consider the following snippet of code in contrast to our previous example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8cf48e95691c3305f2afa12c338f2c7/href">https://medium.com/media/f8cf48e95691c3305f2afa12c338f2c7/href</a></iframe><p>If the JavaScript engine was to execute these lines of code just like it handled the previous one we will have the following sequence:</p><ul><li>The <strong><em>(anonymous) </em></strong>function which is the function that executes the script is called and placed on top of the stack.</li><li>It starts from the top of the file and discovers 3 function declarations, <strong><em>first</em></strong>, <strong><em>second</em></strong> and <strong><em>main</em></strong>.</li><li>On line 16, it sees a call to the <strong><em>main()</em></strong><em> </em>function and adds it to the stack.</li><li><strong><em>main() </em></strong>calls <strong><em>first()</em></strong> and <strong><em>first()</em> </strong>calls <strong><em>setTimeout()</em></strong>. Going with our mental model, <strong><em>setTimeout()</em></strong> will have to pop off the call stack(complete execution) before <strong><em>main()</em></strong> can call <strong><em>second()</em></strong>. This means that our stack should be blocked for <em>one second</em> right?</li></ul><p>Well, this is not the case. <strong><em>setTimeout()</em></strong> strangely disappears from the stack and every other thing continues as though <strong>setTimeout()</strong> never existed on the stack. And after our code execution completes, the callback function in <strong><em>setTimeout() </em></strong>appears out of nowhere and executes. This is demonstrated in the gif below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*LZsd8SFNQmycmZtOCaOD8g.gif" /><figcaption>Visualizing async code execution</figcaption></figure><p>Clearly, this is good news for us. We don’t have to wait an entire second for the next line of code to execute. But how is this possible? Where did the <strong><em>setTimeout()</em></strong> call go to?</p><p>Well, our mental model shouldn’t change. JavaScript is a single-threaded language that executes code using the call stack, one function call at a time. Environments that run JavaScript(<strong><em>browsers </em></strong>on the client-side and <strong><em>nodejs </em></strong>on the server-side) provide a set of APIs that expose data from the environment and do some very useful tasks with these data. These APIs are not part of the core JavaScript language itself. Instead, they are built on top of the core language and they give you some really useful <em>bells and whistles</em> to enhance your JavaScript code. Think about accessing your filesystem with <strong><em>nodejs, </em></strong>The JavaScript engine doesn’t give you any way to access the file system out of the box. Instead, the <strong><em>Native APIs </em></strong>that <strong><em>nodejs </em></strong>exposes enables us to have access to the filesystem. <strong><em>setTimeout()</em></strong> is also a part of the web <strong><em>APIs</em></strong> and each call to <strong><em>setTimeout()</em></strong> is handled by the <strong><em>browser’s</em></strong> (or <strong><em>nodejs’</em></strong>) <strong>APIs</strong>.</p><h4>The event loop</h4><p>If you know about <a href="https://stackoverflow.com/questions/34680985/what-is-the-difference-between-asynchronous-programming-and-multithreading/34681101"><em>multithreading</em></a><em> </em>you will see that apart from assigning tasks to other threads, you will also be responsible for orchestrating the flow of all the threads to ensure that they do not conflict with each other. However, JavaScript has a beautiful way of handling tasks that abstracts the orchestration from us and predictably executes them.</p><p>Whenever we encounter a task that is part of the <strong><em>APIs </em></strong>we talked about previously<em>(</em><strong><em>setTimeout()</em></strong><em> for example)</em>, it delegates this out to the <strong><em>APIs</em></strong> and when these tasks are completed, the callbacks that were passed to them are <a href="https://www.geeksforgeeks.org/queue-data-structure/"><strong><em>queued</em></strong></a> in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop"><strong><em>callback queue</em></strong></a> and the event loop is responsible for dequeuing the callbacks onto the call stack one after the other. This is demonstrated in the gif below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Cyh2ZyZwnY6PtnZE9VNL1Q.gif" /><figcaption>Visualizing async code orchestration with the callback queue and web APIs.</figcaption></figure><p>Hopefully, this is clear now. If at this point you feel lost, I suggest you take a look at <a href="https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4"><em>this article</em></a><em>.</em></p><p>So now, we know how synchronous and asynchronous code is executed but what does that mean for us?</p><h4>Callback hell</h4><p>Consider the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6714cc87c0ca197ccdec6943fd27828c/href">https://medium.com/media/6714cc87c0ca197ccdec6943fd27828c/href</a></iframe><p>The comments from line 4–6 explains the problem with asynchronous code. Looking at the function, there is only one way to get out the data, we have to pass it as a parameter to another function(<a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function"><strong><em>a callback function</em></strong></a>). This is demonstrated below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ae7bbe0a694ea80fd22efcd5e421f0d/href">https://medium.com/media/6ae7bbe0a694ea80fd22efcd5e421f0d/href</a></iframe><p>However, there is a problem with this approach. Imagine we have to log in, get all posts we have and get comments on the posts and then get the users that commented on our posts. It won’t be a pretty sight at all and I will show you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07721a7944f781e16788d4df9f6ac12c/href">https://medium.com/media/07721a7944f781e16788d4df9f6ac12c/href</a></iframe><p>If for some reason, we still need to carry out these instructions with the last user data we got, we will end up nesting callbacks within callbacks and it becomes really difficult to manage.</p><h4>Promises</h4><p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong><em>MDN Web Docs</em></strong></a><strong><em>, </em></strong>A <strong><em>promise</em></strong> is a proxy for a value not necessarily known when the <strong><em>promise</em></strong> is created. It allows you to associate handlers with an asynchronous action&#39;s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a <em>promise</em> to supply the value at some point in the future.</p><p>A <strong><em>promise</em></strong> is in one of these states:</p><ul><li><strong><em>pending</em></strong>: initial state, neither fulfilled nor rejected.</li><li><strong><em>fulfilled</em></strong>: meaning that the operation completed successfully.</li><li><strong><em>rejected</em></strong>: meaning that the operation failed.</li></ul><p><strong><em>Promises</em></strong> give us a different (and cleaner) way to deal with asynchronous code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d1459857b44f20d3686a8101c4bc43/href">https://medium.com/media/64d1459857b44f20d3686a8101c4bc43/href</a></iframe><p>One interesting thing about <strong><em>promises </em></strong><em>is the </em><strong><em>.then()</em></strong><em> </em>method. Since it returns a promise, it is chainable. So this means we can carry out further operations with promises that resolve.</p><p>Now let’s see if we can rescue(refactor) our <em>callback hell-bound</em><strong><em> </em></strong>file from the previous section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb381232727f1c75d14be5c4769f91c8/href">https://medium.com/media/bb381232727f1c75d14be5c4769f91c8/href</a></iframe><p>I am trying to prove to you that promises offer a better syntax and then, the “refactored” file has more lines of code 🤦🏿‍♂️. Well, in reality, the process we simulated will be handled in a cleaner way using <a href="https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data"><strong><em>fetch API</em></strong></a><strong><em> </em></strong>which sends a request to an actual API and gives us a promise which resolves with the data from the API or is rejected with the appropriate error message<strong><em>.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a957288fcf3cdebcce29e2bd0cdc46/href">https://medium.com/media/54a957288fcf3cdebcce29e2bd0cdc46/href</a></iframe><p>While we are happy with the improvements that come with promises, wouldn’t it be nice if we could just write our code in the more readable synchronous manner? Consider the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/758e68333d6630fdb325ca68b763fd64/href">https://medium.com/media/758e68333d6630fdb325ca68b763fd64/href</a></iframe><p>Imagine we did not have to nest callbacks or even chain promises. This will greatly improve readability but going by the mental model we have of the JavaScript call stack, this means that the <a href="https://nodejs.org/uk/docs/guides/dont-block-the-event-loop/"><strong><em>event loop</em></strong></a> will be blocked until login resolves right? So imagine it takes 10seconds to get a user’s data on login, it means that our application will halt for the entire 10secs. By the time we get posts, comments and then the user that created the comment, the time adds up really quickly and we would have frustrated users that will never want to use our app again. But what if I told you that JavaScript gives us some form of <a href="https://en.wikipedia.org/wiki/Syntactic_sugar"><strong><em>syntactic sugar</em></strong></a><strong><em> </em></strong>to write asynchronous code synchronously?</p><h3>Async/Await</h3><p>JavaScript provides a special syntax that allows us to work with promises in a less complicated way.</p><blockquote>There is a caveat that shouldn’t be ignored and that is we can only use this syntax with a special type of function called an async function.</blockquote><h4>Async functions</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b01c225f2aa8201f1950290219e86d5/href">https://medium.com/media/0b01c225f2aa8201f1950290219e86d5/href</a></iframe><p>Async functions are declared using the <strong><em>async </em></strong>keyword as shown above. One interesting thing about async functions is that they always return a promise. We could explicitly return a promise from an async function and this will have the same effect. Notice how in the snippet above, we chain a <strong><em>then() </em></strong>to the <strong><em>func()</em></strong> function call. The return value from <strong><em>func() </em></strong>is automatically passed to <strong><em>console.log() </em></strong>as a parameter.</p><h4>Await keyword</h4><p>Remember what we said about regular synchronous JavaScript functions, they always run to completion before being popped off the call stack. But async functions behave quite differently. We can pause the execution of an async function with the <strong><em>await </em></strong>keyword. Consider the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e2769dd6238aa99986e795316725b58/href">https://medium.com/media/6e2769dd6238aa99986e795316725b58/href</a></iframe><p>From the output of this code, we can see strange behavior. <strong><em>first()</em></strong> is called, and even though it hasn&#39;t completed its execution, the program continues to execute <strong><em>second().</em></strong></p><p>To understand this behavior, let’s take a look at what the <strong><em>await</em></strong> keyword does. When the <strong><em>await</em></strong> keyword is encountered, it makes the interpreter wait until that promise is settled (resolved or rejected). This means that on <strong><em>line 11 </em></strong>of our snippet, the function execution pauses until it gets a value from the<em> </em><strong><em>getCount()</em></strong><em> </em>function. Clearly, this mimics the synchronous code style we all know and love so dearly. The difference is, rather than block the call stack, we proceed to handle other tasks (<strong><em>second()</em></strong>) and then return to complete the execution of <strong><em>first()</em></strong> when we’re done with all other pending tasks.</p><p>This is just a more elegant way of handling promises when compared to <strong><em>promise.then(). </em></strong>Not only is it pleasing to the eyes to read, but it is also a lot easier to write.</p><p>So how can we refactor our codebase to use the <strong><em>async/await</em></strong> syntax? Let’s take a look at one more snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c06cbd06d3ee1a81b80f1aaa789fe5b4/href">https://medium.com/media/c06cbd06d3ee1a81b80f1aaa789fe5b4/href</a></iframe><p>Notice that we had to wrap all the operations in an async function <strong><em>(asyncOperations()) </em></strong>and all we have to do is call the <strong><em>async function</em></strong> and all our promises will execute one after the other within the function.</p><p>It’s really interesting where the JavaScript language is now. Tasks that used to be nightmarish to accomplish have been simplified and the syntax is not as scary as it used to be.</p><p>As developers, it is not enough to jump into new features of our tools without understanding the problems they are trying to solve. I’ve seen a lot of codebases where developers litter the <strong><em>await</em></strong> keyword in a lot of places where they aren’t needed. And this can cause performance problems for our applications.</p><blockquote>Rule of thumb: If the execution of your script doesn’t depend on the result of an asynchronous operation, do not await it.</blockquote><h3>Conclusion</h3><p>In this article, we learned about the JavaScript call stack and how it executes tasks. We also learned that environments in which the JavaScript engine runs (browsers on the client-side and nodejs on the server-side) provide us with <strong><em>APIs</em></strong> we can leverage to write more powerful code. We also learned that callbacks are just nightmarish to deal with and we should use promises instead whenever possible.</p><p>One important thing to note is the fact that we did not consider possible error cases in our examples. This is bad practice. Asynchronous processes are not guaranteed to succeed. We should always handle errors gracefully rather than letting them blow up 💣💥 our code.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d219b6eb8ff" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/asynchronous-javascript-6d219b6eb8ff">Asynchronous JavaScript.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: Memoization.]]></title>
            <link>https://medium.com/swlh/functional-programming-memoization-c2af275a0b1d?source=rss-a0c7eb332492------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2af275a0b1d</guid>
            <category><![CDATA[lexical-scope]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[Chukwudi Ngwobia]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 19:32:18 GMT</pubDate>
            <atom:updated>2020-04-04T15:15:47.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming: Understanding Memoization.</h3><figure><img alt="A PCB with the word CACHE inscribed" src="https://cdn-images-1.medium.com/max/1024/1*fvlMpkpIKmPm6IF_QnmjmQ.jpeg" /><figcaption>CACHE inscribed on a PCB. Source: <a href="https://bit.ly/2w8BYgB">https://bit.ly/2w8BYgB</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>According to <a href="https://en.wikipedia.org/wiki/Memoization"><em>Wikipedia</em></a><em>,</em> memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</p><blockquote>There is a caveat that shouldn’t be ignored; only <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976"><strong>pure functions</strong></a> can be memoized.</blockquote><p>This is an advanced topic so I have curated a list of pre-requisite concepts (with helpful links) to grasp before jumping in. I really recommend going through (and understanding) these topics if you have no prior knowledge of them before jumping into this article.</p><ul><li><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0"><strong><em>Functional Programming</em></strong></a></li><li><a href="https://medium.com/javascript-scene/higher-order-functions-composing-software-5365cf2cbe99"><strong><em>Higher-Order Functions</em></strong></a></li><li><a href="https://code.likeagirl.io/simplified-javascript-getting-started-with-closures-f40f65317d00"><strong><em>Closures</em></strong></a></li><li><a href="https://www.freecodecamp.org/news/recursion-is-not-hard-858a48830d83/"><strong><em>Recursion</em></strong></a></li><li><a href="https://en.wikipedia.org/wiki/Hash_table"><strong><em>Hashmaps</em></strong></a></li></ul><p>For this article, we will use a very interesting mathematical concept, the <a href="https://en.wikipedia.org/wiki/Fibonacci_number"><strong><em>Fibonacci Sequence</em></strong></a><strong><em>.</em></strong></p><p>Simply put, the Fibonacci Sequence is a series of numbers in which any term is the sum of the previous 2 terms.</p><p>So if we start from 0 and 1 (<a href="https://math.stackexchange.com/questions/158699/why-does-the-fibonacci-series-start-with-0-1">people argue that it should start from 1 directly since 1 is the first term in the sequence</a>) the sequence can be fleshed out to read 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ….</p><p>The list can continue for as much as we can count, and to prove this, we are going to write a <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976"><em>pure function</em></a> <em>f(n)</em> that takes in <em>n</em> as a parameter and then returns the <em>nth </em>term of the sequence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23d739920a7a1146a7f2389cc606884e/href">https://medium.com/media/23d739920a7a1146a7f2389cc606884e/href</a></iframe><p>A beautiful function right? If you don’t understand this function, kindly pause and go read <a href="https://www.freecodecamp.org/news/recursion-is-not-hard-858a48830d83/"><em>this article</em></a> again.</p><p>If you’re half as curious as I am (I’d be dead if I was “the cat”), you would try larger numbers like 40, 50 or even higher. I can actually guarantee that after trying 50 (or anything above), you would think twice before running the function again with the same argument 😁🏃🏿‍♂️🏃🏿‍♂️🏃🏿‍♂️. Well, our smart computer has a hard time computing the results as n increases. This is because, as n increases, the function calls become more “expensive”.</p><p>This may sound a bit vague but I think a graphical representation will make things clearer. Below is a sketch of how the function executes for <em>n = 5</em>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*qHHwerYeQmSmcG152nUHLw.png" /><figcaption>The recursive tree created by calling the fibonacci function with n = 5</figcaption></figure><blockquote>As we can see, there is a lot of repetitive computation, <em>f(3)</em> is called twice, <em>f(2)</em> is called three times and so on. And remember for each call, we will still go down the tree to get the final value. Things are already starting to get messy.</blockquote><p>Our lovely computer will get away with <em>f(5)</em> of course and maybe <em>f(10)</em>. But what if we really need to compute the Fibonacci number for higher values of <em>n?</em></p><h4><strong><em>Memoization</em></strong></h4><p>Just like we said earlier, we can use memoization to speed up the computation of functions (the Fibonacci number in this case) by skipping computations we’ve already encountered and instead, read the value directly from the cache. This is possible because our function is a <em>pure function</em>. For the same input, we will always get the same result. This allows us to replace the function call with its resulting value without changing the meaning of the program. And we can confidently do this because we know that our function has no side effects.</p><p>Below is a memoized version of our fibonacci function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f96137f776c015e9efce803b7ade714/href">https://medium.com/media/9f96137f776c015e9efce803b7ade714/href</a></iframe><p>Ok. There’s quite a lot going on here but let me explain…</p><p>The <em>memoizedFibonacci</em> function returns a <strong><em>brand new, </em>smart </strong><em>fibonacci </em>function. And notice we declare a new variable called <em>fibonacci</em> outside the <em>memoizedFibonacci </em>function. <strong><em>This should not be confused with the function returned from the memoizedFibonacci function.</em></strong> The outer fibonacci function holds a reference to the returned <em>fibonacci</em> function. The inner <em>fibonacci</em> function has closure over the <em>cache</em> variable and therefore can store and retrieve data from the cache. This can be demonstrated in a browser console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*czyf1lL-9uCR995CnJw0Rg.png" /><figcaption>A simple demonstration of closures in JavaScript</figcaption></figure><blockquote>Do not be overwhelmed by the image above. It is a very basic demonstration of the closure concept. From the <em>outerFunction </em>we return an object with two methods: <em>increase </em>and <em>decrease</em>. If we execute the <em>outerFunction </em>and store the result in a variable, we can inspect the resulting object and see the properties of the <em>increase </em>and <em>decrease</em> function. Notice the <strong><em>[[scopes]] </em></strong>property, it also has a property called <strong><em>Closure</em></strong>. The C<strong>losure</strong> property lists all the variables available (<em>enclosedVariable </em>in this example) to the function from the parent function’s block scope. And we can’t access this variable from outside the <em>outerFunction. </em>But calling increase or decrease will alter this variable because it was enclosed together with the functions when they were returned from <em>outerFunction.</em></blockquote><p>Back to our <em>fibonacci</em> function with <strong>superpowers</strong>, calling the <em>memoizedFibonacci</em> function will return the <em>fibonacci</em> function enclosed with the <em>cache</em> variable and each execution of the returned function will store its result in the cache.</p><p>The execution steps are now thus:</p><ul><li>check for the input, <em>n </em>in the <em>cache</em>. If it exists, return it. Don’t do any other thing, just return the value because we already know what it is. (<em>Just think about the amount of time this will save us</em>).</li><li>If the value is not in the <em>cache</em>, we calculate it and add the result to our <em>cache</em> for easy retrieval the next time.</li></ul><p>So for every input encountered down the execution tree, save it in the <em>cache (implemented as a hashmap where the inputs are the key and the results are the values) </em>so that the next time it’s seen, we just return from the hashmap rather than execute the time-consuming part of the function.</p><p>Interesting right?</p><p>Now you can see why our computer didn’t run out of breath trying to figure out what the 1000th term of the Fibonacci sequence is.</p><p>Memoization can be applied to other functions as long as they are pure functions and have no <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">side effects</a>. The next step in this article is to write a memoization function that can be applied to any pure function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74506f0a44ac6c9b3acd976054ac2e45/href">https://medium.com/media/74506f0a44ac6c9b3acd976054ac2e45/href</a></iframe><p>Notice that the first call to <em>memoizedFibonacci </em>took approximately 2 seconds to execute. But the next and other subsequent calls with the same input will execute immediately.</p><p>There is one flaw with our memoize function. It only caches the input of the function at the top of the node (<em>40 in this case</em>). Calling <em>memoizedFibonacci(30)</em> will still take some time to execute even though we know we must have encountered it while calculating the 40th Fibonacci number. Here’s why:</p><p>Line 6 executes our function and stores the returned value in the cache, although this caches the return value, it does this just for the value we pass, so if we call <em>memoizedFibonacci(40)</em>, here’s what our cache will look like:</p><pre>{ &#39;40&#39;:   102334155 }</pre><p>To walk around this, we can memoize the <em>fibonacci</em> function itself and then pass it into the <em>memoize</em> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d1fbe104832d935be7c9d2412a34b6/href">https://medium.com/media/13d1fbe104832d935be7c9d2412a34b6/href</a></iframe><p>Notice how even though we have way larger values for <em>n</em> in this example (<em>1000 vs 40</em>), we have significantly less compute time.</p><p>I know you may be thinking, “this is way too messy for me to even dabble into, <strong>Thanks for nothing Chux</strong>”. Well, you’re absolutely right. Apart from the fact that I’m a horrible teacher, the implementation is way too verbose and hard to keep up with. But I’ll show you a much neater way to implement this.</p><h4><em>Decorators</em></h4><p>In its simplest form, a decorator is simply a way of wrapping one piece of code with another — literally “decorating” it. This is a concept you might well have heard of previously as <strong>functional composition</strong> or <strong>higher-order functions</strong>.[<a href="https://www.sitepoint.com/javascript-decorators-what-they-are/">source</a>]</p><p>Decorators are currently a <a href="https://github.com/tc39/proposals#stage-2"><em>stage 2 proposal</em></a><em> </em>in JavaScript and should become a part of the language in a future update.</p><p>But since this isn’t strictly a JavaScript article, I’ll show decorators in action using python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/345d1323f7a96f2512cecfa4fafdc1d3/href">https://medium.com/media/345d1323f7a96f2512cecfa4fafdc1d3/href</a></iframe><p>Neat huh?</p><p>I love decorators so much as they make our code a lot more readable. Notice we didn’t have to memoize the fibonacci function again as the decorator tells the code each time you encounter the fibonacci function (line 8), memoize it. The same implementation written verbosely will end up looking like our previous implementation in JavaScript. I will leave it up to you to write out the verbose implementation in python and feel free to drop it in the comments section.</p><h3>And it’s a wrap…</h3><p>We touched a lot of advanced concepts in this article and if you had a hard time following, I really suggest you take a look at the topics I listed at the beginning of this article. Functional programming can be quite daunting at first approach. And this is simply because of the new terms and concepts you need to wrap your head around. But really, these are really just fancy words. Once you grasp the concepts, you will see how easy it is to mess around with pure functions and solve complex problems (Quickly and Elegantly).</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2af275a0b1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/functional-programming-memoization-c2af275a0b1d">Functional Programming: Memoization.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>