<?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 Ruckaiya Mira on Medium]]></title>
        <description><![CDATA[Stories by Ruckaiya Mira on Medium]]></description>
        <link>https://medium.com/@ruckaiya.awf5?source=rss-f863729be932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VZdd1CiCAg8ZcMr3oswYZw.jpeg</url>
            <title>Stories by Ruckaiya Mira on Medium</title>
            <link>https://medium.com/@ruckaiya.awf5?source=rss-f863729be932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:03:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ruckaiya.awf5/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[#5 Welcome to Callback Hell]]></title>
            <link>https://medium.com/@ruckaiya.awf5/5-welcome-to-callback-hell-8d603ed69bf4?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d603ed69bf4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[callback-hell]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 20:00:25 GMT</pubDate>
            <atom:updated>2022-07-06T20:00:25.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is the 5th part of a series of essays. Read <a href="https://medium.com/@ruckaiya.awf5/4-our-first-ajax-call-xmlhttprequest-64b03c00c21">Part 4 here</a>: <a href="https://medium.com/@ruckaiya.awf5/4-our-first-ajax-call-xmlhttprequest-64b03c00c21">Our First AJAX Call XMLHttpRequest</a></h4><p>So in the last article, we did a simple AJAX call to fetch data from a country’s API. We created a function for that. And as we call the function multiple times, multiple AJAX calls were made at the same time. They were basically running in parallel and we could not control which one finished first, remember that?</p><p>However, in this article, let’s create a sequence of AJAX calls, so that the second one runs only after the first one has finished.</p><p>Here’s what we’re gonna do….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAiCNp3jJdWX4UFLboFwMQ.gif" /><figcaption>Rendering a country and all of its neighbouring countries</figcaption></figure><p>In the countries data here, there is some property of the bordering countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*nM3TOcV8Igd0tzm2ePQJlg.png" /><figcaption>Borders property</figcaption></figure><p>You see, this one here has the codes MMR and IND — that’s because these 2 are bordering countries of Bangladesh. What we will do now is after the first AJAX call is completed, we will get this border, and then based on the code(s), we will also render the neighboring countries beside the original country. And so in this case, the second AJAX call really depends on the first one, because the data about neighboring countries, is of course a result of the first call. Without the first call, we wouldn’t even know which data to fetch in the second call. Hence, what we need to implement is a sequence of AJAX call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OdMNF_aFqkpHvQW02KU_g.png" /><figcaption>2 Sequential AJAX calls</figcaption></figure><p>I refactored yesterday’s code so that our code and functions are organized, cleaner and easy to read.</p><p>I’ve kept the HTML content that gets displayed on our webpage as a result of the AJAX calls in its own function called<strong>renderCountry().</strong></p><p><em>If you scrutinize the code you’ll understand what’s going on here because it’s simple and straightforward.</em></p><blockquote>[raw code provided at the end of the article]</blockquote><p>Here, we basically send off the request, the request then fetches the data in the background. Once that is done, it will omit the load event. The event listener is waiting for that event, and <strong>as soon as the data arrives, callback function in it will be called</strong>.</p><p>In yesterday’s example, we only just did one request and got one response back, And that’s how it’s gonna work when all we do is to access an API. However, if it’s a WEB PAGE that we’re accessing, then there will be many more requests and responses. And that’s because when we do the first request, all we get back is just the initial HTML file. That HTML file will then get scanned by the browser for all the assets that it needs in order to build the entire Web page like JavaScript, CSS files, image files, or other assets. And then for each different file, there will be a new HTTP request made to the server. When all the files have finally arrived, then the Web page can be rendered in the browser, according to the HTML, CSS and JavaScript specifications.</p><p>Now, if we want these requests to be made in a specific predefined order, then we would basically have to chain the requests. Which means to make the second request only after the first request has finished. This results in something called as the <strong>CALLBACK HELL</strong>!</p><p>Today what we just did was <strong>we made an AJAX call for a country, then once we get the data then we call for the neighbour of that country:</strong></p><p>getCountryAndNeighbour(‘germany’);</p><blockquote>So here, we attached the first callback function. And then <strong>inside of that</strong>, we have yet another one. So we have nested callbacks. But if we have to find the neighbour of the neighbours then we need to add callback inside a callback so on… this results to something called as the CALLBACK HELL.</blockquote><p>The callback hell is when we have a lot of nested callbacks in order to execute asynchronous tasks in sequence. And in fact, this happens for all asynchronous tasks, which are handled by callbacks (for example, a nested setTimeout function) and not just AJAX calls.</p><p>Now, the problem with callback hell is that it makes our code look very messy. But even more important, it makes our code harder to maintain, and very difficult to understand, now the harder it is to understand code and to reason about the code, the more difficult it will be to add new features.</p><p>Since ES6, there is actually a way of escaping callback hell by using something called PROMISES.</p><p>ajax-with-callback.js</p><pre>const getCountryAndNeighbor = function (country) {<br>    //AJAX call for country<br>    const request = new XMLHttpRequest();<br>    request.open(&#39;GET&#39;, `<a href="https://restcountries.com/v3.1/name/$%7Bcountry%7D%60">https://restcountries.com/v3.1/name/${country}`</a>);<br>  <br>    request.send();<br>  <br>    request.addEventListener(&#39;load&#39;, function () {<br>      const [data] = JSON.parse(this.responseText);<br>      console.log(data);<br>  <br>      // Render country:<br>      renderCountry(data);<br>  <br>      //Get country neighbour<br>      let neighbour = 0;<br>      if (!data.borders) {<br>        return; // If no neighbour then simply return<br>      } else {<br>        for (let neighbour of data.borders) {<br>          //AJAX call for neighbour<br>          const requestNeighbour = new XMLHttpRequest();<br>          requestNeighbour.open(<br>            &#39;GET&#39;,<br>            `<a href="https://restcountries.com/v3.1/alpha/$%7Bneighbour%7D%60">https://restcountries.com/v3.1/alpha/${neighbour}`</a> //alpha used in link instead of name bcz neighbour is the code<br>          );<br>          requestNeighbour.send();<br>  <br>          requestNeighbour.addEventListener(&#39;load&#39;, function () {<br>            const [dataNeighbour] = JSON.parse(this.responseText);<br>            // console.log(dataNeighbour);<br>            renderCountry(dataNeighbour);<br>          });<br>        }<br>      }<br>    });<br>  };<br>  <br>  const renderCountry = data =&gt; {<br>    const lang = Object.values(data.languages).join(&#39;,&#39;);<br>        const currencies = Object.values(data.currencies).map((currency) =&gt; currency.name).join(&#39;,&#39;);<br>        const borders = Object.values(data.borders).map(border =&gt; border).join(&#39;,&#39; + &#39; &#39;);<br>        <br>        const html = `<br>       <br>        &lt;table&gt;</pre><pre>&lt;tr&gt;<br>                &lt;td&gt;Country Flag:&lt;/td&gt;<br>                &lt;td&gt;&lt;img src=&quot;${data.flags.png}&quot;/&gt;&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Country Name:&lt;/td&gt;<br>                &lt;td&gt;${data.name.common}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Capital city:&lt;/td&gt;<br>                &lt;td&gt;${data.capital}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Region:&lt;/td&gt;<br>                &lt;td&gt;${data.region}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Continent:&lt;/td&gt;<br>                &lt;td&gt;${data.continents}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Borders:&lt;/td&gt;<br>                &lt;td&gt;${borders}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Population:&lt;/td&gt;<br>                &lt;td&gt;${data.population} ~ ${+(data.population / 1000000).toFixed(1)} M&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Language: &lt;/td&gt;<br>                &lt;td&gt; ${lang} &lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Currency: &lt;/td&gt;<br>                &lt;td&gt; ${currencies} &lt;/td&gt;<br>            &lt;/tr&gt;<br>        &lt;/table&gt;<br>        &lt;br/&gt;<br>        `;<br>        const divEl = document.createElement(&#39;div&#39;);<br>        divEl.innerHTML = html;<br>        <br>        document.body.appendChild(divEl);<br>      <br>  };</pre><pre>// getCountryAndNeighbor(&#39;bangladesh&#39;);<br>// getCountryAndNeighbor(&#39;canada&#39;);<br>getCountryAndNeighbor(&#39;germany&#39;);</pre><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot; /&gt;<br>    &lt;title&gt;Asynchronous JavaScript ~ AJAX&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script defer src=&quot;ajax.js&quot;&gt;&lt;/script&gt;<br>    &lt;script defer src=&quot;ajax-with-callback.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>If you like to read my articles … ♥️ follow me &amp; subscribe to my email list on medium: <a href="https://medium.com/@ruckaiya.awf5">https://medium.com/@ruckaiya.awf5</a> to be notified of the publication of the next article.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d603ed69bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#4 Our First AJAX Call XMLHttpRequest]]></title>
            <link>https://medium.com/@ruckaiya.awf5/4-our-first-ajax-call-xmlhttprequest-64b03c00c21?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b03c00c21</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 23:29:14 GMT</pubDate>
            <atom:updated>2022-07-05T23:29:14.374Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here is the link to <a href="https://medium.com/@ruckaiya.awf5/3-asynchronous-javascript-ajax-and-apis-in-node-js-286eb50416cd">3rd article</a> of this series: <a href="https://medium.com/@ruckaiya.awf5/3-asynchronous-javascript-ajax-and-apis-in-node-js-286eb50416cd">Asynchronous Javascript, AJAX and APIs in Node.js</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnlpBrN3Fba1BKfLrjj2rw.png" /><figcaption>AJAX Sends an XMLHttpRequest To a Server</figcaption></figure><p>Don’t get intimidated by seeing this code!</p><p>I’ll explain each and every line of code from beginning to end.</p><p>So now that we know about AJAX and APIs, let’s actually make our first API call.</p><p>In today’s story, we’re going to build a small application to demonstrate how to code to make AJAX and API calls.</p><p>Our application will contain data about a certain country, and this data about the countries are actually gonna come from a third party online API — (just as we learned it in the last lesson). I think it feels really magical, and next level, to be able to do this.</p><p>The API that I selected for this project is — <a href="https://restcountries.com/">https://restcountries.com/</a></p><p>And so let’s now start working on this.</p><p>Now in JavaScript, there are actually <strong><em>multiple ways of doing AJAX calls</em></strong>. But we’re gonna start with the most old school one. And that’s called the <strong>XMLHttpRequest</strong> function.</p><p>Now again, as I mentioned, this is the old school way of doing AJAX in JavaScript. But I’m still showing it to you for two reasons.</p><ul><li>First, I want you to know that XMLHttpRequest exists because you might actually need it in the future.</li><li>And second, I want to show you how AJAX calls used to be handled with events and callback functions. And so only after that, we should move on to a more modern way of handling asynchronous JavaScript, which is gonna be a feature called <strong><em>Promises.</em></strong></li></ul><h4>Steps to send an HTTP request</h4><p>There are three steps for a client from sending an HTTP request to receiving an HTTP response:</p><ul><li>The client writes the HTTP request message and sends it to the server.</li><li>The server accepts the HTTP message, processes it, and then returns the HTTP response message to the client.</li><li>The client receives the HTTP response message, parses the message, and retrieves the data.</li></ul><p>The HTTP request message contains:</p><ul><li>HTTP Methods. Include GET , POST , PATCH …</li><li>URL</li><li>Header</li><li>Body</li></ul><p>The HTTP response message contains:</p><ul><li>Status Code</li><li>Header</li><li>Body</li></ul><p><em>We’ll learn more about Status Code, Header and Body later in the node.js series. For now just know what HTTP request and response contains.</em></p><p>In our JavaScript code, all we need to do is:</p><ul><li><strong>Set</strong> Method, URL, Header, and Body for the request message during the sending HTTP message stage.</li><li>In receiving an HTTP response, read information such as Status Code, Header, Body, and so on from the response message and process logically.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7ElvaiEhFarVfB07yXbzg.png" /><figcaption>First 2 steps to send an HTTP request</figcaption></figure><p>In the example above, we <strong>made a GET request</strong> to <strong>restcountries API</strong> to get basic information about a specific country.</p><ol><li>XMLHttpRequest is a constructor that generates an instance object for sending an HTTP request and receiving an HTTP response. Let’s call this instance object request.</li><li>The request.open method is used to set the Method and URL of the HTTP request message. It <strong>takes two arguments</strong>, <strong><em>the first being the HTTP Method and the second being the destination URL.</em></strong></li><li>Finally, <strong>we send the HTTP request through the </strong><strong>request.send method</strong>. (<em>This method can take a single parameter to set the Body of the HTTP message. When we call this method, the browser will actually start sending the HTTP request….. more on HTTP Body later</em>)<em>.</em></li></ol><h4>Why we don’t assign variable to the result?</h4><p>Now, in order to get the result, we can’t do something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R879RtN8M8Witxv2TYYwlw.png" /><figcaption>Don’t set send request into a variable;</figcaption></figure><p>And the reason why we cannot set some variable to this result here is because the <strong>result is</strong> simply <strong>not there yet</strong>. This AJAX call that we just sent off here, is being done in the background, while the rest of the code keeps running. And so this is the asynchronous, non-blocking behavior that we talked about in the last lesson. Instead, what we need to do is to <strong>register a callback on the request object for the load event</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fa1Puo92fBzdlXnbdOqKkA.png" /></figure><p>So request, and then again, our old friend, .addEventListener. And here on the request, we will wait for the load event. Here, we basically again send off the request. And that request then fetches the data in the background. And then once that is done, it will emit the load event. Hence, using this event listener, we are waiting for that event. And so as soon as the data arrives, this callback function here will be called.</p><p>Then we logged the result to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96vUY2hP5LBTlwg4EuBYxw.png" /><figcaption>The original data comes as a big string of text in an array containing an object. So we console logged to check the type of data we got.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*KNJqloUPO0hqMPOUAI8TaA.png" /><figcaption>The response i.e. the data that we got is JSON</figcaption></figure><p>Now, we need to convert this to an actual JavaScript object.</p><p>Because what we have here right now is JSON. Remember that JSON is basically just a big string of text. And so what we need to do here is to then convert that. We do that by <strong>JSON.parse(this.responseText)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5kzbx01NjPcE9JO_3kkLg.png" /></figure><h4>Let’s take a look at the data. You’ll see that this is actually an array containing one object.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*fcnoIKYrWMdB6TwNGLe-1g.gif" /><figcaption>I called getCountryData function thrice down in my code, that’s why you’re seeing 6 logs from 2 console logs for each country.</figcaption></figure><p>Let’s destructure that to get the object — <strong>const [data] = JSON.parse(this.responseText);</strong></p><p>The <strong>this keyword</strong> inside of this function <strong>is the request</strong>. (<em>So we could also do </em><em>request. but let’s just use the this keyword</em>). And this response is in the property responseText . Again, this property here is of course, only gonna be set <strong>once the data has actually arrived. </strong>If we tried to set it out after request.send(), then that wouldn’t work. We can still try that just to see request.responsetext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXr_xlvQtxqXBs1M-LrXKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*HDNb4YDKv11V4mweOxO8Tw.png" /></figure><p>But from the second log function, we have our first data. That’s great, and as you see, this is the result of our very first AJAX call. You can see that this kind of looks like a bunch of data about Bangladesh indeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Unr-m7_EuMobw2RDsJ_idw.png" /><figcaption>Printing response into DOM</figcaption></figure><p>The rest of the code attached above should be self explanatory.</p><p>I’ve created a template literal to print the data from our API call in a table form.</p><p>To explain what <strong>Object</strong>.<strong>values</strong>() is doing here….. <strong>Object</strong>.<strong>values</strong>() method is returning an array containing all the object’s own property values. <em>If you analyze the received data object carefully, you’ll see arrays and nested objects in some of the properties of this mega data object!! Object.value() method helps in getting the values of the keys in objects.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*uY6CLJoFXJkWUJr0qhDiSg.png" /><figcaption>Calling getCountryData function</figcaption></figure><p>By calling these functions here thrice, we will basically have three AJAX calls happening at the same time. In parallel, so to say.</p><p>And if we reload this page a couple of times, you’ll see that they appear in a different order each time. That’s because the data arrives at a slightly different time, each time we’re loading the page. In fact, this really shows the non-blocking behavior in action.</p><p>As we call <strong>getCountryData</strong> here with Bangladesh, for the very first time, it sends off this request, and then JavaScript moves on in the code right away. And so it goes right to this next line. And this, of course, fires off another AJAX call immediately, way before the data of Bangladesh has actually arrived. We will have 3 AJAX calls happening at the same time. And so whichever one arrives first, will then fire the load event first.</p><p>If the first one is to AJAX call for Canada, well, then the first element that’s going to be printed in the DOM will, of course, be the one from Canada.</p><p>And only after that the data for Bangladesh arrive. And then the callback function is called with the data of Bangladesh. And the same would be true no matter how many other requests we would fire off here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zL-Bg32jE7MlhEl2RMAfwg.gif" /><figcaption>Showing what happens after page reloads</figcaption></figure><p>Now, if we actually wanted these requests to be made in a specific, predefined order, then we would basically have to <strong>chain the requests</strong>. This means making the second request only after the first request has finished. And that’s actually what we’re gonna do in the next lesson so that I can show you something that we <strong><em>developers call callback hell</em></strong>.</p><h3>FINAL CODE:</h3><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot; /&gt;<br>    &lt;title&gt;Asynchronous JavaScript ~ AJAX&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script defer src=&quot;ajax.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>ajax.js</p><pre>const getCountryData = function (country) {<br>    const request = new XMLHttpRequest();<br>  <br>    request.open(&#39;GET&#39;,`<a href="https://restcountries.com/v3.1/name/$%7Bcountry%7D%60">https://restcountries.com/v3.1/name/${country}`</a>);</pre><pre>request.send();<br>    // console.log(request.responseText);</pre><pre>request.addEventListener(&#39;load&#39;, function () { <br>        // console.log(this.responseText);<br>        // console.log(JSON.parse(this.responseText));<br>        const [data] = JSON.parse(this.responseText); <br>        // console.log(data);</pre><pre>const lang = Object.values(data.languages).join(&#39;,&#39;);<br>        const currencies = Object.values(data.currencies).map((currency) =&gt; currency.name).join(&#39;,&#39;);<br>        const borders = Object.values(data.borders).map(border =&gt; border).join(&#39;,&#39; + &#39; &#39;);<br>        <br>        const html = `<br>       <br>        &lt;table&gt;</pre><pre>&lt;tr&gt;<br>                &lt;td&gt;Country Flag:&lt;/td&gt;<br>                &lt;td&gt;&lt;img src=&quot;${data.flags.png}&quot;/&gt;&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Country Name:&lt;/td&gt;<br>                &lt;td&gt;${data.name.common}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Region:&lt;/td&gt;<br>                &lt;td&gt;${data.region}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Continent:&lt;/td&gt;<br>                &lt;td&gt;${data.continents}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Borders:&lt;/td&gt;<br>                &lt;td&gt;${borders}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Population:&lt;/td&gt;<br>                &lt;td&gt;${data.population} ~ ${+(data.population / 1000000).toFixed(1)} M&lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Language: &lt;/td&gt;<br>                &lt;td&gt; ${lang} &lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;tr&gt;<br>                &lt;td&gt;Currency: &lt;/td&gt;<br>                &lt;td&gt; ${currencies} &lt;/td&gt;<br>            &lt;/tr&gt;<br>        &lt;/table&gt;<br>        &lt;br/&gt;<br>        `;<br>        const divEl = document.createElement(&#39;div&#39;);<br>        divEl.innerHTML = html;<br>        <br>        document.body.appendChild(divEl);<br>        console.log(html);<br>    });<br>};</pre><pre>getCountryData(&#39;bangladesh&#39;);<br>getCountryData(&#39;canada&#39;);<br>getCountryData(&#39;saudi&#39;);</pre><h4>If you like to read my articles … ♥️ follow me &amp; subscribe to my email list on medium: <a href="https://medium.com/@ruckaiya.awf5"><em>https://medium.com/@ruckaiya.awf5</em></a><em> </em>to be notified of the publication of the next article.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b03c00c21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#3 Asynchronous Javascript, AJAX and APIs in Node.js]]></title>
            <link>https://medium.com/@ruckaiya.awf5/3-asynchronous-javascript-ajax-and-apis-in-node-js-286eb50416cd?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/286eb50416cd</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 21:40:52 GMT</pubDate>
            <atom:updated>2022-07-05T15:50:13.589Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here is the link to 2nd article of this series: <a href="https://medium.com/@ruckaiya.awf5/2-running-javascript-outside-the-browser-a06576c5d45c">Running Javascript Outside the Browser</a>.</h4><h4>JavaScript is asynchronous in nature and so is Node.</h4><p>Let’s start by understanding what asynchronous javascript actually is, and also learn about the most popular use cases of asynchronous javascript, which is basically to make so-called AJAX calls to APIs.</p><p>Now, to understand what asynchronous javascript code actually is, we first need to understand what synchronous code is, which is basically the opposite of asynchronous.</p><p>Most of the codes that we write as a beginner in javascript are synchronous code, and <strong>synchronous simply means that the code is executed line by line</strong>, in the exact order of execution that we defined in our code, just like in this small example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*kVklLiHTynAg6rgyvmyXlA.png" /><figcaption>Example of synchronous code</figcaption></figure><p>So as the first line of code is reached in the execution, it is simply executed in the execution of thread. (<em>Now don’t worry about this execution of thread. It’s not important here, it’s just to make a point of synchronous versus asynchronous code, as you will see next</em>).</p><p>All you need to know is that the execution of thread is part of the execution context, which does actually execute the code in the computer’s processor.</p><p>But anyway, back to our example code….. the next line (i.e. 2nd line) of code is executed and then the next one, all in sequence.</p><p>Each line of code always <strong>waits</strong> for the previous line to finish execution. Now this can create problems when one line of code takes a long time to run.</p><p>For example, in the 3rd line of code, we have an <strong>alert statement</strong>, which creates an alert window. Now, as we all know, this alert window will block the code execution, right? Nothing will happen on the page until we click that OK button. And only then, the code can continue executing.</p><p>And so the alert statement is a perfect example of a long running operation, which blocks execution of the code.</p><p>So again, only after we click OK, the window disappears and the next line can run. This is hopefully a nice illustration of the problem with synchronous code.</p><p>Now, most of the time synchronous code is fine and makes perfect sense. But imagine that execution would have to wait for example, for a five second timer to finish. That would just be terrible, right?</p><p>Because meanwhile, nothing on the page would work during these five seconds.</p><p>And so that’s where asynchronous code comes into play.</p><p>This example contains the five-second timer that I just mentioned. And if you want, you can pause reading here for a minute and analyze this code before we move on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*gFK17nwggpCN3FwR6gevCA.png" /><figcaption>Example of asynchronous code</figcaption></figure><p>Now, the first line of code is still synchronous here, and we also move to the second line in a synchronous way. But here we encountered the <strong>setTimeout function</strong>, <strong>which will basically start a timer in an asynchronous way</strong>. So this means that the timer will essentially run in the background without preventing the main code from executing. We also register a callback function, which will not be executed now, but only after the timer has finished running. Now this callback function that I just mentioned is asynchronous javascript. And it is asynchronous because <strong>it’s only going to be executed <em>after</em> a task that is running in the background finishes execution</strong>. And in this case, that is the timer. So this callback that we just talked about is registered, and then we immediately move on to the next line.</p><p>The main code is <strong>not</strong> being blocked and execution does not wait for the asynchronous timer to finish its work. And that’s the big difference between synchronous and asynchronous code.</p><p>Previously we had to wait for the user to click on the alert window to continue execution. And again, that’s because<strong> alert is blocking synchronous code</strong>, but now with this timer, the callback is actually asynchronous. And so it’s only going to be executed after the timer has finished. And so, therefore, we say that it’s non-blocking because, in the meantime, the rest of the code can keep running normally. Now, when the timer finally finishes after five seconds, the callback function will finally be executed as well. So you’ll see that <strong>this callback runs after all the other code</strong>, even though in the code, it doesn’t appear at the end. And so basically an action was deferred into the future here in order to make the code non-blocking.</p><p>So in summary, asynchronous programming is all about coordinating the behavior of our program over a certain period of time. And this is essential to understand. Asynchronous literally means not occurring at the same time. And so that’s what asynchronous programming is all about. All right.</p><p>Now, as we saw in the async example code, we needed a callback function to implement this asynchronous behavior, right? However, <strong>that does not mean that callback functions automatically make code asynchronous</strong>. That is just not the case.</p><p>For example, the Array map method accepts a callback function as well, but that doesn’t make the code asynchronous.</p><p><strong>Only certain functions</strong> such as setTimeout <strong>work in an asynchronous way</strong>. We just have to know which ones do and which ones don’t, okay? But please understand this very important fact that <strong>callback functions alone do not make code asynchronous</strong>, that’s essential to keep in mind.</p><p>But anyway, in order to really understand this, let’s see another example. This example is about loading an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gm5Hj7f8MQPgg5krS2x-tA.png" /><figcaption>2nd example of asynchronous code</figcaption></figure><p>So the first two lines run in a synchronous way, one after the other. In the second line, we <strong>set the source attribute of the image</strong> that we selected in the first line. And <strong>this operation is actually asynchronous</strong>. Setting the source attribute of any image is essentially loading an image in the background while the rest of the code can keep running. And this makes sense, right? Imagine that it’s a huge image, we wouldn’t want our entire code to wait for the image to load. And that’s why setting the source attribute was implemented in javascript in an asynchronous way.</p><p>Now once the image has finished loading, a load event will automatically be emitted by javascript. And we can then listen for that event in order to act on it.</p><p>Listening for the load event is exactly what we do here in the next line as well. Here we used <strong>addEventListener</strong> and to register a callback function for the load event.</p><p>Just like in the previous example, we provide a callback function that will be executed once the image has been loaded and not right away because again, all this code is non-blocking.</p><p>So <strong>instead of blocking, execution moves on right to the next line immediately</strong>.</p><p>Then once the image is completely loaded, it’s displayed on the webpage and the load event is admitted.</p><p>And since we’re listening for that event, our callback function is finally executed.</p><p>So once more, we deferred an action into the future making the code asynchronous and non-blocking.</p><p>And now at this point, I believe that you have a pretty good understanding of asynchronous code.</p><p>There’s just one more important thing that I need to mention which is the fact that <strong>event listeners alone do not make code asynchronous, just like callback functions alone, <em>do</em> also <em>not</em> make code asynchronous</strong>.</p><p>For example, an event listener listening for a click on a button is not doing any work in the background. It’s simply waiting for a click to happen, but it’s not doing anything. And so there is no asynchronous behavior involved at all. Now what makes this code example asynchronous is simply the fact that the image is loading asynchronously in the background, but not the fact that we are listening for the load events to happen. So <strong>what matters is the asynchronous behavior of a task</strong>, like running a timer or loading an image. And there are more examples of asynchronous behavior in javascript like the APIs, or AJAX calls.</p><p>And AJAX calls are probably the most important use case of asynchronous javascript. Let’s see what AJAX is all about.</p><p>So <strong>AJAX</strong> stands for <strong>Asynchronous Javascript and XML</strong>, and basically it <strong>allows us to communicate with remote web servers in an asynchronous way</strong>. Now in practice, we make AJAX calls in our code in order to request some data from a web server dynamically — without reloading the page so that we can use that data in our application dynamically.</p><p>For example, right in the next article, we’re going to make AJAX calls to request data about countries. And we can then use that data about countries to build a small application that shows us information about the country that we’re currently in. And the possibilities and use cases are endless, but more about that in next.</p><p>For now, let’s quickly understand how AJAX works.</p><p>Let’s say that we have our javascript application running in the browser, which is also called the client. And we want the application to get some data from a web server. And let’s say the data about countries that I was talking about earlier.</p><p>So with AJAX, we can do an HTTP request to the server, which has this data. And the server will then send back a response containing that data that we requested. And this back and forth between Client and server all happens asynchronously in the background, just the way we learned before.</p><p>And there can even be different types of requests, like GET requests to receive data or POST requests to send data to a server. (<em>But there is a whole lesson about this a bit later to really show you how it all works in detail).</em></p><p>Now, when we’re asking a server to send us some data, this server usually contains a web API. And this API is the one that has the data that we’re asking for. An API is something pretty important, and so let’s now see what an API and web APIs actually are.</p><p>First of all, <strong>API stands for Application Programming Interface</strong>. In general terms, and on the very high level of abstruction, <strong><em>an API is basically a piece of software that can be used by another piece of software in order to basically allow applications to talk to each other and exchange information</em></strong>. And that’s true not only for web development and javascript, but for programming in general.</p><p>Now in javascript and web development, there are countless types of APIs, like the DOM API. These are called APIs because they are a self-contained piece of software that allow other pieces of software to interact with them.</p><p>Also, we can always implement a small and simple API in a class where we make some methods available as a public interface. So again, objects made from a class can be seen as self-contained encapsulated pieces of software that other pieces of software can interact with. And that fits the definition of API, right?</p><p>But now let’s talk about the important type of API that we are actually interested in when we use AJAX. And those are APIs that I like to call <strong>Online APIs</strong>.</p><p><strong><em>An online API is essentially an application running on a web server, which receives requests for data, then retrieves this data from some database and then sends it back to the client</em></strong>.</p><p>When building applications in practice, we simply call these online APIs, and many people will also call these APIs Web APIs, or again, just simply API. The term Online API is actually a term that I came up with myself because the term Web API is actually also used for other things. Now of course we can build our own Online APIs, but that requires back-end development — development with servers and databases and all that. And this is what we’re learning in this course.</p><p>We also use 3rd-party APIs — APIs that other developers make available for us most of the time for free. Let’s imagine that you’re building a traveling application, and you have a database with different destinations and tours that you’re offering. So on your own server, you could build your own API that can receive requests from your front end application in javascript and send back the results. That would be your own API hosted on your own server. But that alone would probably not be enough to build a complete application. And so you could also use some 3rd-party APIs. And there are really APIs for everything. In our example, travel application, you could use an API to get weather data in your destinations, data about the destination countries themselves, data about flights, and currency conversion. And you could even use APIs to send emails or text messages or embed Google maps into your applications. As you can see, the possibilities are really endless with APIs, and we can even say that APIs are what made the modern web as you know it possibly in the first place. So using APIs in javascript is super popular and everyone does it all the time, and so that’s why I’m explaining to you all these details.</p><p>Now just to finish, let’s quickly talk about API data formats. AJAX stands for Asynchronous Javascript and XML. Remember? So the X there stands for XML and XML is a data format, which used to be widely used to transmit data on the web.</p><p>However, these days basically no API uses XML data anymore. The term AJAX is just an old name that got very popular back in the day and is still used today, even though we don’t use XML anymore. So instead, most APIs these days use the JSON data format.</p><p><strong>JSON</strong> <strong>is</strong> the most popular data format today because it’s basically <strong>just a javascript object, but converted to a string</strong>. And so, therefore, it’s very easy to send across the web and also to use in javascript once the data arrives.</p><p>All right. Now that we know what asynchronous javascript is, and also what AJAX and APIs are, let’s finally use all this in practice and make our very first AJAX call in the next article.</p><p>Follow me &amp; subscribe to my email list on medium: <a href="https://medium.com/@ruckaiya.awf5"><em>https://medium.com/@ruckaiya.awf5</em></a><em> </em>to be notified of the publication of the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=286eb50416cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#2 Running Javascript Outside the Browser]]></title>
            <link>https://medium.com/@ruckaiya.awf5/2-running-javascript-outside-the-browser-a06576c5d45c?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06576c5d45c</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 22:47:55 GMT</pubDate>
            <atom:updated>2022-07-03T21:37:51.059Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here is the link to <a href="https://medium.com/@ruckaiya.awf5/whats-node-js-and-why-we-use-it-9c06105bbcc9"><em>1st article</em></a> of this series: <a href="https://medium.com/@ruckaiya.awf5/whats-node-js-and-why-we-use-it-9c06105bbcc9">What’s node.js and Why we use it</a>.</h4><p>I hope that you have node installed on your computer at this point and if you don’t, then you can directly install it from its website: <a href="https://nodejs.org/en/">https://nodejs.org/en/</a></p><p>Now we’ll go ahead and use node for the very first time. And to get started, create a folder called <strong>NODE_SERIES</strong> in your desktop. Next, open this empty folder in visual studio code.</p><p>We are going to interact with node using the command line and for that I’m going to use the built-in terminal that vs code has. I’m always going to use the terminal that is built-in right into vs code so that we don’t have to jump around between different windows so much.</p><p>To start writing some node code here in the console all you have to do is to <strong>write</strong> <strong>node</strong> given that you have node.js installed on your computer and <strong>then</strong> just <strong>hit enter</strong> and this will then open up the <strong>node REPL</strong> which stands for <strong>Read-Eval-Print Loop</strong>.</p><p>Here we can write javascript code just like in a normal terminal, for example, we can define variables, expressions etc, that’s because at the end of the day node.js is really just a javascript runtime as we just saw before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kaM7MYDFuJJUDHG7cuxaQ.png" /><figcaption>Node commands in REPL</figcaption></figure><p>Node.js supports es6 in all the newer versions out of the box without any problem that’s because we’re not running this javascript in any browser but it will always run on the server. In fact, we just took javascript out of the browser and we’re running it inside of this node application.</p><p>If we want to exit this REPL i.e. Read-Eval-Print Loop that node gives us, there are different ways of doing it.</p><p>First one is to <strong>write</strong> dot exit (<strong>.exit</strong>). This exits the node process, the REPL and <strong>to start it again- just type <em>node</em>, hit enter</strong> and that’s it.</p><p>And if you want to clear your terminal <strong>hit command k</strong> (in mac), <strong>type cls</strong> (in windows) and that will then clear up the command line.</p><p>We used <strong>dot exit</strong> to exit the REPL but we can also hit <strong>control d</strong> <em>(and that’s </em><strong><em>NOT</em></strong><em> </em><strong><em>command</em></strong><em> (in mac) it is really </em><strong><em>control</em></strong><em>),</em> so control d will do the same.</p><p>Let’s quickly enter <strong>node</strong> again because there’s some more stuff that I want to show you.</p><p>If you <strong>hit tab twice</strong> you can see all the global variables that are available in node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpQbqhIyeKtm4bK-pOhEyg.png" /><figcaption><em>Global variables that are available in node</em></figcaption></figure><p>You have all the kind of stuff that we’re already used to, like the array constructor, the string constructor, math, number, etc but then there’s also all kinds of stuff that belongs to node, for example,<strong> http</strong>, <strong>fs</strong> or <strong>crypto</strong> and these are <strong>node modules </strong>that we’re going to talk more about a bit later but for now you see that we have all kinds of global variables that we can access whenever we want in node.js.</p><p>Another nice trick is the underscore variable.</p><p>For example, if you calculate 3 times 8 in the terminal, 3 * 8 gives 24 and now if you use <strong>underscore times 2 </strong>(<strong> _ * 2</strong>,<strong> </strong>i.e.<strong> 24 * 2</strong>) in the next line, we get 48.</p><p>That means that <strong>underscore is basically your previous result</strong>.</p><p>We had 24 and so, underscore in the 2nd calculation is 24 and 24 times 2 gives 28.</p><p>In the same manner, underscore plus 2 (here underscore’s value is 48 + 2) gives 50 and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qC6pamiD8dhm_4ho3v6Jjg.png" /><figcaption>Use underscore to get previous result</figcaption></figure><p>Finally, the tab that you just pressed a few moments ago, you can also press that for example, on one of the constructors that we already know like string.</p><p><strong>String dot</strong> and <strong>then by hitting tab twice </strong>you can see all the methods or properties that are available to us. You have, for example, the <strong>length</strong> or <strong>hasOwnProperty</strong> and all these kinds of methods that we know already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAi7H4zH0WVwu7WusjZ_uQ.png" /><figcaption>How to see all methods and properties of any constructor inside node</figcaption></figure><p>Now to exit the REPL, all we have to do is</p><p>For mac: <strong>hit control d <em>or</em> type .exit </strong>then<strong> command k</strong> to clear the console.</p><p>For windows: <strong>hit Ctrl + d <em>or</em> type .exit </strong>then<strong> type cls </strong>to clear the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4mtZ5si_bpINtLinRKfFg.png" /></figure><p>And that’s all I wanted to show you in this very very first coding with node.</p><p>Follow me &amp; subscribe to my email list on medium: <a href="https://medium.com/@ruckaiya.awf5"><em>https://medium.com/@ruckaiya.awf5</em></a><em> </em>to be notified of the publication of the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06576c5d45c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#1 What’s node.js and Why we use it]]></title>
            <link>https://medium.com/@ruckaiya.awf5/whats-node-js-and-why-we-use-it-9c06105bbcc9?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c06105bbcc9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 16:07:23 GMT</pubDate>
            <atom:updated>2022-07-01T18:40:24.961Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a Node.js, Express.js, and MongoDB tutorial series of articles for beginners who want to enhance their skill on Node.js and step toward back-end Web Development.</p><p>In this Node.js series, I will cover Node.js, Express.js, and MongoDB from scratch. Most importantly this node.js series is absolutely beginner-friendly. The only prerequisite is you must know JavaScript.</p><p>I will publish a new article every two days and little by little you will learn everything there is to know about Node.js.</p><p>To not miss anything follow me on medium: <a href="https://medium.com/@ruckaiya.awf5">https://medium.com/@ruckaiya.awf5</a></p><p>Now before diving into some node.js code let’s do a high level overview of what node.js actually is, what we use it for, and why we use node instead of other technologies.</p><p>So the official definition is that <strong><em>node.js is a javascript runtime built on google’s open source v8 javascript engine</em></strong>. Now what does that actually mean!!</p><p>Well, let’s start by trying to understand what a <strong>javascript runtime</strong> and the <strong>v8 engine</strong> actually are. So you have probably already used javascript before and it was probably always just inside a browser because any browser natively understands html, css and javascript and no matter if you write vanilla javascript or some javascript framework like react or angular code, that’s all just javascript that gets executed right in the browser. So in this case <strong><em>the browser is then the javascript runtime</em></strong>.</p><p>But what if we could take javascript out of the browser and simply execute our javascript code somewhere else without all the restrictions that we have in the browser?</p><p>Well it turns out that we actually can and the solution for this as you can guess is called node.js and so node.js is just another javascript runtime.</p><p>It’s just like a container like an environment in which a program written in javascript can be executed but outside of any browser.</p><p>It’s actually a bit more complex than this of course but for now, this is enough.</p><p><em>Who actually does execute the code if not the browser?</em></p><p>And that’s where the v8 engine developed by Google comes into play because that is exactly where javascript code will be parsed and run in node.js.</p><p>So I hope that now the definition of node.js being a javascript runtime built on the v8 javascript engine makes a lot more sense and again this is just a very high level overview of what node is and how it works.</p><p>We are going to go into a lot of detail about how node really works behind the scenes in future but at this point I just want you to get a quick overview so that you can start learning the fundamentals of node.js in practice.</p><p>Now that we have javascript outside of the browser in a kind of standalone environment, which is node.js, we can do so many more things with javascript that were completely impossible before like accessing the file system or better networking capabilities are now possible with node.js and all these factors together give us the perfect conditions for using node.js as a web server, meaning that now we can finally use javascript on the server side of web development in order to build fast highly scalable network applications for powering the back end of our websites or web applications and this is absolutely fantastic and game changing for web development.</p><p>Let’s now take a look at some use cases for node and why it’s such a great fit for back-end development.</p><p>The first thing that we need to talk about is the fact that node applications are so fast and so scalable because <strong><em>node.js is single threaded and based on an event-driven non-blocking I/O model which makes node.js very lightweight and efficient</em></strong>.</p><p>That, of course, sounds super complicated I know but once more we’re gonna talk about exactly what all of this means a bit later in the series but for now just keep in mind that node is perfect for building super fast and scalable data-intensive web applications and that makes node.js a perfect fit for building all different kinds of applications like building an API with a database behind it and preferably a non-relational NoSQL database like mongodb and this is actually exactly what we’re going to do later in this series as we dive deeper and deeper into node.js but there is of course all sorts of other apps that we can build like data streaming applications such as youtube or netflix, real-time chat apps or even server-side web applications where the entire content is simply generated right on the server.</p><p>So as you see the possibilities really are endless but there is also a type of apps that we should not build with node and this is when our app needs some super heavy server side processing like heavy image manipulations, video conversion, file compression or anything like that and you will learn why that is once we dive deeper into how node actually works. In this case we’re better off using something like ruby on rails, php or python because node.js just wasn’t developed for these use cases and although there are solutions for dealing with them we should always use the right tool for the task at hand.</p><p>So these are the types of applications that we can and cannot build using node.js and if you choose to use node, well, then you are in good company because many top companies like netflix, uber, paypal, ebay and many many more have already started using node.js, which really proves that the technology is stable enough at this point to be used in production and of course there are more reasons for using node and the biggest one is probably that using the same language across your entire stack both on the front end and the back end is a lot easier for you or for your team.</p><p>First, you don’t have to learn a new programming language for building your backend and also you don’t have to keep switching back and forth between languages, which will make the entire building process faster and more efficient, believe me it’s really really amazing to be able to use javascript to build your entire application from start to finish.</p><p>Another great reason for using node is that there is a huge library of open source packages or modules as we can also call them available for everyone for free. It’s called <strong>npm</strong> and you’ve probably heard of it or even used it already.</p><p>Finally, it’s also good to know that there is a huge active community of node developers out there that are constantly improving node.js and helping beginners and so you can really rely on the technology for all your projects in the years to come.</p><p>So that was a very brief intro and overview of node.js and some of its use cases.</p><p>We will next use node to create a very simple web server and build an extremely simple API so that you can get familiar with the basic principles of node development.</p><h4>✅ TODO TIME:</h4><p>Install <a href="https://nodejs.org/en/">node.js</a> in your computer. <em>(Download the </em><strong><em>LTS</em></strong><em> version not the </em><strong><em>Current</em></strong><em> one)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c06105bbcc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#1 What is React and How it works — Learn React Series]]></title>
            <link>https://medium.com/@ruckaiya.awf5/1-what-is-react-and-how-it-works-learn-react-series-de7bc2a3284b?source=rss-f863729be932------2</link>
            <guid isPermaLink="false">https://medium.com/p/de7bc2a3284b</guid>
            <category><![CDATA[basic-react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ruckaiya Mira]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 17:54:59 GMT</pubDate>
            <atom:updated>2022-06-29T17:54:59.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>#1 What is React and How it works — Learn React Series</h3><h4>Why do we code in React in simple English.</h4><p>React JS — Currently the most popular web library. I am launching a <em>Learn React Series</em> with this article on Medium.</p><p>In this series, I will try to explain the basic things of React JS in simple English language from the beginning.</p><p>In this article, I have tried to explain what React is, why we will learn React and the basic concept of React with examples. Hopefully, this article will be useful for any beginner who has a basic idea about JavaScript. Also, if you follow the next articles of this series continuously, I hope you will understand React JS and will be able to work.</p><p>React JS, in short, we call it react.</p><p>What will be there in this article?</p><p>Everything about the react library, step by step from the start till the end, including examples so that you can understand it practically.</p><p>According to the Stack Overflow Developer Survey 2020, React’s position and popularity among the most popular web frameworks’ was after JQuery and it was only increasing day by day since then that in 2021’s survey React topped that list.</p><p>“What is React?” should not be our first question but “why learn React?”. What is so special about this javascript library that according to the 2021 survey, <strong>40.14 percent</strong> of respondents reported to be using React.</p><p>Well if we see the official website of React JS, it states that React is a Javascript library for building user interfaces. Here two things are important 1) Javascript library and 2) User Interfaces.</p><p>Library means a collection of codes that are reused to make our applications. In the same way, React is a collection of vanilla javascript codes which we use to make websites, mobile applications and even desktop applications’ user interfaces.</p><p>When we talk about an application, there are two parts 1) front-end or user interface 2) back-end (where all the logic is).</p><p>Front-end is where the user interacts such as browsing, clicking, submitting forms etc and it is this the front-end that responds to these interactions with the help of the back-end. In the back-end, we basically have the data and there is where complex business logic like authentication, authorization, data manipulation etc happens.</p><p>React is not concerned with back-end but front-end, which means its work is to respond to user interactions as well as display and render information.</p><p>Now if we talk about the web then we know Javascript is the web’s default programming language. React is not a programming language but just a Javascript library, which means React somehow speaks in Javascript language. It is an open source project, that means if we want we can see its source code and you will see that there is nothing else except pure Javascript.</p><p>That’s why it is important to know Vanilla JavaScript and Modern JavaScript syntaxes to work with React. You don’t need to be a boss in JS in order to learn React but at least need to know the basics.</p><p>Now the question is React was introduced in 2013 so before that didn’t we build websites?</p><p>Of Course we did using vanilla JS and JQuery. We used to handle user interfaces and user interactions with this two. So what was the need for React when JQuery was popular since the work was getting done. To answer that question we will build a small UI with vanilla JS and discover why React is useful and what extra benefits we get using React.</p><p><strong>Create a folder</strong> on your desktop and inside it create 2 more files — <strong>index.html</strong> and <strong>script.js</strong>.</p><p>In index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;React Tutorial&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>      &lt;div&gt;<br>        &lt;h1 id=&quot;display&quot;&gt;0&lt;/h1&gt;<br>        &lt;div&gt;<br>          &lt;button id=&quot;button&quot;&gt;Increment +&lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;script src=&quot;./script.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Our goal is to click on the increment button and the counter number will increase by one.</p><p>For that in the <strong>script.js</strong> file, first, we select the button and then in the button’s click event, we run a function that will increase the counter number by one.</p><p>To do this:</p><ol><li>Write a variable name number and set the initial value of the counter number to zero.</li><li>Then using the query selector method we will select the increment button.</li><li>Now to listen this button’s click event, use addEventListener and in its callback increase the number by one by writing number++.</li><li>Next, select the p tag and set its textContent value to the number.</li><li>Now when you click on the increment button, the counter number increases by one.</li></ol><p>In script.js</p><pre>let number = 0;</pre><pre>const display = document.querySelector(&quot;#display&quot;);<br>const button = document.querySelector(&quot;#button&quot;);</pre><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  number++;<br>  display.textContent = number;<br>});</pre><p>Now the question is what is the problem here when everything is working fine.</p><p>Well, the problem is, for larger applications it is not scalable.</p><p>For example, at the moment we have <strong>only one</strong> counter. That’s why it doesn’t seem to be a problem but in practical applications, there will be many HTML files and we might need to use similar counters like this in multiple places.</p><p>Let’s say, we need another counter here in this example.</p><p>What would we have done to add this second counter? We’d have had to take another one of this div in fig:1 and <strong>change the ids</strong> of them. In the JS file, we’d have <strong>needed two number variables</strong> as well as<strong> two buttons and p tags</strong>. Finally, we’d have <strong>needed two addEventListener for two buttons to work</strong>. You see, in order to do the same thing twice, we have to change so many things. Maybe you can maximize it by taking a single function and passing the parameter there but no matter what you do, you have to select these Html elements separately and this can be error-prone. This does not scale well for larger applications and we have to duplicate the same code if more counters are needed and our application will not be managed faster.</p><p>For a long time, JavaScript developers had to face this problem as the complexity of the user interface increased and managing the code became difficult.</p><p>The same problem was faced by Facebook engineers because a huge website like facebook’s user interface is very complex and was getting very difficult to manage with vanilla javascript.</p><p>That’s when they started to work on it and in 2011 Facebook’s software engineer Jordan Walke created the first prototype of React JS and named it Fax js. It was first used in 2011 on Facebook’s news feed and on Instagram in 2012.</p><p>Jordan was influenced by an HTML component framework XHP-JS of PHP and made react.</p><p>In 2013 Fax.js was renamed to React.js and was made open source.</p><p>So from then on, react.js started to become popular and big companies started to use react actively in their front-end, including Netflix, Whatsapp, Instagram and many more.</p><p>There are currently over 3 million websites that use React world wide.</p><p>Now we will see in the case of our example how React solves the problem. We will create the same UI using React instead of vanilla JS.</p><p>First, <a href="https://reactjs.org/">go to react.js</a> website then in the <a href="https://reactjs.org/docs/getting-started.html">Docs</a> section go to <a href="https://reactjs.org/docs/add-react-to-a-website.html"><strong><em>Add React to a Website</em></strong></a><strong><em>. </em></strong>There you can see three steps on how we can add react to our website.</p><ol><li>Create another HTML file in your folder called <strong>react.html.</strong></li><li>Add a div with an id root: <em>inside this div our react application will be generated.</em></li><li>Then add the required script tags at bottom of the HTML file.</li></ol><p><strong>In the script tags you can see two things have been obtained <em>1) react </em></strong>and<strong><em> 2) react dom</em></strong></p><p>react.html</p><pre><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;React Tutorial&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><pre>&lt;!-- Load React. --&gt;</pre><pre>&lt;!-- Load React. --&gt;<br>    &lt;!-- Note: when deploying, replace &quot;development.js&quot; with &quot;production.min.js&quot;. --&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/react@18/umd/react.development.js">https://unpkg.com/react@18/umd/react.development.js</a>&quot; crossorigin&gt;&lt;/script&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/react-dom@18/umd/react-dom.development.js">https://unpkg.com/react-dom@18/umd/react-dom.development.js</a>&quot; crossorigin&gt;&lt;/script&gt;</pre><pre>&lt;!-- Load JSX --&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/babel-standalone@6/babel.min.js">https://unpkg.com/babel-standalone@6/babel.min.js</a>&quot;&gt;&lt;/script&gt;</pre><pre>&lt;!-- Load our React component. --&gt;</pre><pre>&lt;script type=&quot;text/babel&quot; src=&quot;./Increment.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>React library will generate a HTML library for us and React dom library will render it in the browser DOM.</p><p><strong>Where will it generate and render it?</strong></p><p><strong><em>In root HTML div block.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*9Wp4dN-sBpmf4lxPr7zWXw.png" /><figcaption>HTML div block with id=”root”</figcaption></figure><p>That’s all you need to write in HTML.</p><p>Now we will only write javascript.</p><p>To write Javascript create a new js file named <strong>increment.js.</strong></p><p>In the HTML file import the increment.js file.</p><p><strong>The increment.js file has access to react because in </strong><strong>react.html file the </strong><strong>increment.js file is included after react.</strong></p><p>You might be wondering why React and React DOM are separate?</p><p>That’s because react is not only made for browsers. React is a platform agnostic library. When we use react library in mobiles we use another library called React Native instead of React DOM and are able to render the UI made by the same react library in mobile interfaces. That’s why the two packages are kept separately.</p><p>In the browser, we use React DOM. In fact, 90% of work is done by react, React DOM will only be used for printing. Let&#39;s see how.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>ReactDOM.render(&lt;h1&gt; Hello World &lt;/h1&gt;, domContainer);</pre><p>First, we will select the root div element and store it in a <strong>domContainer</strong> variable.</p><p>Then <strong>call the render method</strong> of ReactDom and this method receives two parameters.</p><p>In the <strong>first parameter</strong>, we have to mention <strong><em>what you want to print</em></strong> so I gave ‘Hello World’ and in the <strong>second parameter</strong>, we have to mention <strong><em>where you want to print </em></strong>— and for that give domContainer (which is the root div).</p><p>React DOM will just render the text ‘Hello World’ in the root div. You can see ‘Hello World’ on the screen. If you inspect this, you can see the text is present in the root div. Here we are only rendering text but you can render anything if you want.</p><p>Using the React library we can create useful things plus render them and these are called <strong>React elements</strong>.</p><p>React library provides some functions using which we can make React elements, for example <strong>React.createElement()</strong> function.</p><p>Let’s create a React element.</p><p><em>Comment the code you wrote previously</em></p><p>First create a variable name <strong>myElement</strong> and equate it to <strong>React.createElement()</strong>.</p><p>In the <strong>first parameter</strong>, <strong><em>we mention what element to create</em></strong> so I will go with a div. In the <strong>second parameter</strong>, <strong><em>we mention the data that you want to pass</em></strong> in the div, at the moment let’s consider no data so we are passing null. In the <strong>third parameter</strong>, <strong><em>we mention what content will be there inside the element</em></strong> meaning inside the div and I am writing ‘Hello world’. Using React we created a react element and the content inside the element is ‘Hello world’.</p><p>Notice we have created a React element but not an HTML element and then instructed the ReactDOM to render <strong>myElement</strong> in root div.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>const myElement = React.createElement(&quot;div&quot;, null, &quot;Hello React Element&quot;);</pre><pre>ReactDOM.render(<br>  myElement,<br>  domContainer<br>);</pre><p>If you inspect and see inside the root div there is another div with the content ‘Hello world’.</p><p>Now, what if we want to add a p element inside the div? Then in the third parameter instead of the text, another React element is given as content.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>const myElement = React.createElement(&quot;div&quot;, <br>                  null, React.createElement(&quot;p&quot;, null, &quot;Hello &lt;p&gt; Element&quot;));</pre><pre>ReactDOM.render(<br>  myElement,<br>  domContainer<br>);</pre><p>What if we want to add two p elements inside the div?</p><p>Then we <strong>can give an array of elements in the third parameter</strong>. Refer fig:8</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>const myElement = React.createElement(&quot;div&quot;, <br>                  null, <br>                  [</pre><pre>React.createElement(&quot;p&quot;, null, &quot;Hello &lt;p&gt; Element&quot;),<br>                  React.createElement(&quot;p&quot;, null, &quot;Hello 2nd &lt;p&gt; Element&quot;)<br>                ]);</pre><pre>ReactDOM.render(<br>  myElement,<br>  domContainer<br>);</pre><p>That’s the job of React Library. It just creates any React element and the ReactDOM receives the React elements which makes them HTML elements for browser DOM, meaning it renders the elements in the browser.</p><p>What is the benefit to create elements like this with React?</p><p>Conversely, the syntax is more complex. Well, forget React, when we write markup in the HTML file then DOM creates HTML elements this way for us for example, I made a p element using document.createElement which has a content of ‘Hello world’ and rendered it in the root div. If we inspect it you can see the root div has the p element with the text ‘Hello world’.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>let p = document.createElement(&quot;p&quot;);<br>p.innerHTML = &quot;Hello p element&quot;;<br>domContainer.appendChild(p);</pre><pre>// const myElement = React.createElement(&quot;div&quot;, <br>//                   null, <br>//                   [React.createElement(&quot;p&quot;, null, &quot;Hello &lt;p&gt; Element&quot;),<br>//                   React.createElement(&quot;p&quot;, null, &quot;Hello 2nd &lt;p&gt; Element&quot;)<br>//                 ]);</pre><pre>// ReactDOM.render(<br>//   myElement,<br>//   domContainer<br>// );</pre><p>This is the way we write it in Html because this syntax is easy for us. Though we write in this way browser parses HTML and creates its DOM by calling createElement.</p><p>Html just makes our work easy by giving easy syntax so that we can make our UI faster. In the same way, React makes elements using its<strong> createElement function</strong> and <strong>then creates a separate DOM for itself using these elements</strong>.</p><blockquote>Remember it is a <strong>separate DOM</strong> and in React language we call it Virtual DOM.</blockquote><p>Normally we make HTML elements indirectly by using markup syntax. In the same way React provides us with a markup syntax which we can use to make React elements and the syntax’s name is <strong>JSX</strong> - Javascript XML, which looks 90% like HTML but it is not HTML.</p><p>If we write this HTML using JSX then <strong>we write it in first brackets and store it in a variable</strong> that’s it. This will ultimately call the createElement and make React elements for us.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>const myElement = (<br>  &lt;div&gt;<br>    &lt;h1 id=&quot;display&quot;&gt;0 &lt;/h1&gt;</pre><pre>&lt;button id=&quot;button&quot;&gt;Increment +&lt;/button&gt;<br>  &lt;/div&gt;<br>)</pre><pre>ReactDOM.render(myElement, domContainer);</pre><p>The above code is equivalent to the code below.</p><pre>const domContainer = document.querySelector(&quot;#root&quot;);</pre><pre>const myElement = React.createElement(&quot;div&quot;, null, <br>  React.createElement(&quot;h1&quot;, {<br>  id: &quot;display&quot;<br>  }, <br>  &quot;0 &quot;), <br>  React.createElement(&quot;button&quot;, {<br>    id: &quot;button&quot;<br>  }, <br>  &quot;Increment +&quot;));</pre><pre>ReactDOM.render(myElement, domContainer);</pre><p>Thank God we don’t have to write code like this, we write JSX.</p><p>Now the question is we are writing the JSX syntax in js file meaning in javascript but javascript does not understand this syntax neither is it available in ECMAScript specification, then?</p><p>Well, that’s why we have to use the transpiler: <strong>Babel.</strong></p><p>Babel will transform this JSX syntax into vanilla javascript.</p><p>On Babel’s website go to <a href="https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&amp;build=&amp;builtIns=false&amp;corejs=3.21&amp;spec=false&amp;loose=false&amp;code_lz=Q&amp;debug=false&amp;forceAllTransforms=false&amp;shippedProposals=false&amp;circleciRepo=&amp;evaluate=false&amp;fileSize=false&amp;timeTravel=false&amp;sourceType=module&amp;lineWrap=true&amp;presets=env%2Creact%2Cstage-2&amp;prettier=false&amp;targets=&amp;version=7.18.7&amp;externalPlugins=&amp;assumptions=%7B%7D"><strong><em>Try it out</em></strong></a> and paste your JSX code. You can see Babel transpile the code into vanilla javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENmVxQo1ahIFXIGZ6qzvAA.png" /><figcaption>Babel transpiles JSX into vanilla javascript</figcaption></figure><p>That’s why if you’ve noticed I’ve added 3rd script in <strong>react.html</strong>.</p><p>Let’s use babel in our code for that. Go to <a href="https://babeljs.io/docs/en/babel-standalone">Docs</a> and in the Babel script section copy the babel script tag and paste it into the HTML file.</p><p>And in our main js file, which we will traspile using Babel, write type=“text/babel” in the script tag.</p><pre>&lt;!-- Load JSX --&gt;<br>    &lt;script src=&quot;<a href="https://unpkg.com/babel-standalone@6/babel.min.js">https://unpkg.com/babel-standalone@6/babel.min.js</a>&quot;&gt;&lt;/script&gt;</pre><pre>&lt;!-- Load our React component. --&gt;</pre><pre>&lt;script type=&quot;text/babel&quot; src=&quot;./Increment.js&quot;&gt;&lt;/script&gt;</pre><p>We know by default that the type of js file is text/javascript but when we write text/babel the js file goes to babel first then it transpiles the code and ultimately we get javascript.</p><p>If we see the output of the increment button then you can see it works fine but still we did not get the answer to why we are using React. We will get there soon.</p><p>This counter is not a dumb counter. It has functionalities. It should work when clicked so where should we add them?</p><p><em>To be continued in part 2….</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de7bc2a3284b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>