<?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 Shan on Medium]]></title>
        <description><![CDATA[Stories by Shan on Medium]]></description>
        <link>https://medium.com/@shan32157?source=rss-4ab69d535ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YIbJksMmmB3t3s7s.jpg</url>
            <title>Stories by Shan on Medium</title>
            <link>https://medium.com/@shan32157?source=rss-4ab69d535ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:40:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shan32157/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[Day 16: Storage]]></title>
            <link>https://medium.com/@shan32157/day-16-storage-57409e251c26?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/57409e251c26</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[indexeddb]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 10:28:00 GMT</pubDate>
            <atom:updated>2024-08-04T10:28:00.882Z</atom:updated>
            <content:encoded><![CDATA[<h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*mBkfrBHPIfYcmBEUQG4mow.png" /><figcaption>JS Fundamentals in 30 days:Day 16: Storage</figcaption></figure><h3>CLient-Side Storage vs. Server-Side Storage</h3><p>When we talk about “client-side”, it it often referred to the browser, therefore, <strong>client-side storage</strong> means to store data on the browser. On the other hand, <strong>server-side storage</strong> means to store data on the server.</p><h4>Why do we need to store data on the client side?</h4><p>You may sometimes see some personalized content on a website, such as your name, your preferences, etc. This is because the website stores some data on your browser. This is useful because:</p><ul><li>It can improve the user experience by providing personalized content.</li><li>It can reduce the load on the server by storing some data on the client side.</li></ul><p>There are several ways to store data on the client side:</p><ul><li>Cookies</li><li>Web Storage</li><li>IndexedDB</li></ul><p>Let’s take a look at each of them.</p><h3>Storage quotas</h3><p>In order to reduce the risk of users being tracked across websites, browser stores data per <strong>origin (combination of protocol, host, and port)</strong> in the most cases.</p><p>Data for an origin can be stored in two ways:</p><ul><li>Best-effort: Default way of storing data for an origin.</li><li>Persistent: An origin can be opt-in to store data persistently.</li></ul><p>But how much data can be stored?</p><ul><li>Cookies: Depends on the browsers and disk space.</li><li>Web Storage (localStorage and sessionStorage): Limited to 10 MiB of data maximum on all browsers.Browsers can store up to 5 MiB of local storage, and 5 MiB of session storage per origin.</li></ul><h4>What happens when the storage limit is reached?</h4><p>Browser will throw a QuotaExceededError exception, so we can implement a try-catch block to handle this exception or to use the navigator.storage.estimate() to check how much storage is available.</p><p>Now that’s take a look at each of the storage methods.</p><h3>Cookies</h3><p>When you visit a website, most of them will ask something like “Do you accept cookies?” like image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RXr1V2xH20hFUcutqnvhA.png" /><figcaption>Do you accept cookies example</figcaption></figure><p>Cookies is a old way of storing data on the client side, and it is often related to personal privacy. It stores a small amount of data on the browser, we can create new cookies, read cookies, and delete cookies or modify them.</p><p>For example, when you sing in (send credentials) to a website, the website will create a cookie to store your session information. This is how the website knows you are logged in, even if you refresh the page or visit another page.</p><h4>Main uses of cookies:</h4><ul><li>Session management</li><li>Personalization</li><li>Tracking</li></ul><h4>Why it is an old way of storing data?</h4><p>Because cookies need to be sent to the server with every request, which can slow down the website. Also, cookies have a limit of 4KB, which is not enough for storing large data.</p><h3>Web Storage</h3><p>It is a new way of storing data on the client side, it can store a key-value pair in the browser. There are two types of Web Storage:</p><ul><li>Local Storage</li><li>Session Storage</li></ul><h4>Local Storage</h4><p>It persists even when the browser is closed and reopened, it has no expiration date, and it is stored across browser sessions.</p><h4>Session Storage</h4><p>On the other hand, Session Storage is available only for the duration of the page session. It is deleted when the page session ends.</p><p>Here is how we can use Local Storage:</p><pre>// Set data to local storage<br><br>localStorage.setItem(&quot;name&quot;, &quot;John Doe&quot;);<br><br>// Get data from local storage<br><br>const name = localStorage.getItem(&quot;name&quot;);<br><br>// Remove data from local storage<br><br>localStorage.removeItem(&quot;name&quot;);<br><br>// Modify data from local storage<br><br>localStorage.setItem(&quot;name&quot;, &quot;Jane Doe&quot;);<br><br>// Clear all data from local storage<br><br>localStorage.clear();</pre><p>Here is how we can use Session Storage:</p><pre>// Set data to session storage<br><br>sessionStorage.setItem(&quot;name&quot;, &quot;John Doe&quot;);<br><br>// Get data from session storage<br><br>const name = sessionStorage.getItem(&quot;name&quot;);<br><br>// Modify data from session storage<br><br>sessionStorage.setItem(&quot;name&quot;, &quot;Jane Doe&quot;);<br><br>// Remove data from session storage<br><br>sessionStorage.removeItem(&quot;name&quot;);<br><br>// Clear all data from session storage<br><br>sessionStorage.clear();</pre><h4>Synchronous in nature</h4><p>Both localStorage and sessionStorage are synchronous in nature, if we want to set, get or remove data, the operation will be performed synchronously, means that it will block the JavaScript code execution until the operation is completed, so this might be a potential performance issue, therefore we need to be careful when using them.</p><h3>IndexedDB</h3><p>So is there a way of storing data in asynchronous way? Yes, there is, and it is called IndexedDB. If the performance is a concern, we can use <strong>IndexDB</strong> instead of Web Storage.</p><p>In short, IndexDB solves the performance issue of Web Storage by providing an asynchronous way of storing data, including files and blobs.</p><h4>Transactional Database System</h4><p>Like an SQL-based Relational Database Management System (RDBMS), IndexedDB is a transactional Database System, however, the difference is that IndexedDB is a JavaScript-based object-oriented database, which means it allows us to store and retrieve objects that are indexed with a <strong>key</strong>.</p><p>Let’s see a simple example to show how to add, search and delete an employee.</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;Example: Using IndexedDB&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;IndexedDB Example&lt;/h1&gt;<br>  &lt;div&gt;<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; id=&quot;name&quot; placeholder=&quot;Name&quot;&gt;<br>      &lt;input type=&quot;number&quot; id=&quot;age&quot; placeholder=&quot;Age&quot;&gt;<br>      &lt;button onclick=&quot;addAnEmployee()&quot;&gt;Add Employee&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;input type=&quot;number&quot; id=&quot;searchEmployee&quot; placeholder=&quot;Search ID&quot;&gt;<br>      &lt;button onclick=&quot;getAnEmployee()&quot;&gt;Search Employee&lt;/button&gt;<br>      &lt;button onclick=&quot;deleteAnEmployee()&quot;&gt;Delete Employee&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;span id=&quot;result&quot;&gt;&lt;/span&gt;<br>  &lt;/div&gt;<br><br>  &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>// Initialize db <br>let db;<br>const dbName = &#39;MyDB&#39;;<br>const objectStoreName = &quot;Employees&quot;;<br><br>// Open DB with name and version<br>const request = indexedDB.open(dbName, 1);<br>// Use onerror to log any errors<br>request.onerror = (e) =&gt; {<br>  console.error(&quot;DB Error:&quot; + e.target.error);<br>};<br>// Use onsuccess to log success message<br>request.onsuccess = (e) =&gt; {<br>  // Assign the result to the database variable to use it later<br>  db = e.target.result;<br>  console.log(&quot;DB Opened Successfully&quot;);<br>};<br><br>// Use onupgradeneeded to create object store<br>request.onupgradeneeded = (e) =&gt; {<br>  db = e.target.result;<br>  // Create object store<br>  const objectStore = db.createObjectStore(objectStoreName, { keypath: &#39;id&#39;, autoIncrement: true });<br>  objectStore.createIndex(&quot;name&quot;, &quot;name&quot;, { unique: false });<br>  objectStore.createIndex(&quot;age&quot;, &quot;age&quot;, { unique: false });<br>};<br><br>const getAnEmployeeById = (id, action) =&gt; {<br>  const transaction = db.transaction([objectStoreName], action);<br>  const objectStore = transaction.objectStore(objectStoreName);<br>  const request = objectStore.get(id);<br><br>  return request;<br>};<br><br>// Add an employee to db<br>const addAnEmployee = () =&gt; {<br>  // Get id from html<br>  const name = document.getElementById(&#39;name&#39;).value;<br>  const age = document.getElementById(&#39;age&#39;).value;<br><br>  // transaction is used to interact with the db<br>  // We need to specify the object store we want to interact with<br>  // readwrite is used to add data<br>  const transaction = db.transaction([objectStoreName], &#39;readwrite&#39;);<br><br>  // Get the object store<br>  const objectStore = transaction.objectStore(objectStoreName);<br><br>  // Add data to the object store with name and age as key value pairs<br>  const request = objectStore.add({ name, age });<br><br>  // error or success handler<br>  request.onerror = (e) =&gt; {<br>    document.getElementById(&#39;result&#39;).innerHTML = &quot;Error Adding Data&quot;;<br>  };<br><br>  request.onsuccess = (e) =&gt; {<br>    document.getElementById(&#39;result&#39;).innerHTML = &quot;Data Added Successfully&quot;;<br>  };<br>};<br><br><br><br><br>// Get an employee from db by name<br>const getAnEmployee = () =&gt; {<br>  // Make sure the id is an integer<br>  const id = parseInt(document.getElementById(&#39;searchEmployee&#39;).value);<br>  const request = getAnEmployeeById(id, &#39;readonly&#39;);<br><br>  // error or success handler<br>  request.onerror = () =&gt; {<br>    document.getElementById(&#39;result&#39;).innerHTML = &quot;Error Getting Data&quot;;<br>  };<br><br>  request.onsuccess = (e) =&gt; {<br>    const employee = e.target.result;<br>    if (!employee) {<br>      document.getElementById(&#39;result&#39;).innerHTML = &quot;No Data Found&quot;;<br>    }<br>    if (employee) {<br>      document.getElementById(&#39;result&#39;).innerHTML = `Name: ${employee.name} Age: ${employee.age}`;<br>    }<br>  };<br>};<br><br><br>// Delete an employee<br>const deleteAnEmployee = () =&gt; {<br>  const id = parseInt(document.getElementById(&#39;searchEmployee&#39;).value);<br>  const transaction = db.transaction([objectStoreName], &#39;readwrite&#39;);<br>  const objectStore = transaction.objectStore(objectStoreName);<br>  const request = objectStore.delete(id);<br><br>  request.onerror = () =&gt; {<br>    document.getElementById(&#39;result&#39;).innerHTML = &quot;Could not delete! Please try again&quot;;<br>  };<br><br>  request.onsuccess = () =&gt; {<br>    document.getElementById(&#39;result&#39;).innerHTML = &quot;Employee deleted Successfully&quot;;<br>  };<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57409e251c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 15: Promise]]></title>
            <link>https://medium.com/@shan32157/day-15-promise-2fcbad6cd1bb?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fcbad6cd1bb</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 02:55:38 GMT</pubDate>
            <atom:updated>2024-07-23T02:55:38.289Z</atom:updated>
            <content:encoded><![CDATA[<h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*tcx546Fz0j5W09CeNIAITA.png" /><figcaption>JS Fundamentals in 30 days — Promise</figcaption></figure><h3>Asynchronous vs. Synchronous Programming</h3><p>Before we jump into the topic of Promise, let’s first understand some of the important concepts of async, sync programming and single-threaded and multi-threaded programming.</p><h4>Asynchronous Programming</h4><p>Operations can be initiated without waiting for previous operations to complete. This allows for non-blocking execution.</p><h4>Synchronous Programming</h4><p>Operations are executed <strong>sequentially</strong>, one after another. Each operation must complete before the next one starts.</p><h3>Single-threaded vs. Multi-threaded Programming</h3><p>In CS, a <strong>thread</strong> of execution is the smallest sequence of programming instructions that can be managed independently by a scheduler, which is typically a part of the operating system.</p><h4>Single-threaded</h4><p>It is the processing of one command of at a time.</p><h4>Multi-threaded</h4><p>Multithreading’s execution model that allows multiple threads to exist within the context of one process. It can also be applied to one process to enable parallel execution on a multiprocessing system.</p><h4>Single-threaded in Sync Programming model</h4><p>In a single-threaded environment, a thread is assigned to one task and starts working on it. Once the task completes then it it available to take up the next task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*t99ZdTkxUDkHymWg5k-HEg.png" /><figcaption>Single-threaded in Sync Programming model</figcaption></figure><h4>Multi-threaded in Sync Programming model</h4><p>Have multiple threads which can take up tasks and working on it. This means that we have a pool of threads and tasks, but each thread can only work on one task at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*pMCMPyopYXXznfT-iK_xZg.png" /><figcaption>Multi-threaded in Sync Programming model</figcaption></figure><h4>Single-threaded in Async Programming model</h4><p>We know that when we use single-threaded in sync programming model, the task is executed one after another, in other words, the tasks need to be completed in order, but in async programming model, the tasks are interleaved to each other like the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EM-Ad6-hSS8RVH8H5Hp8pA.png" /><figcaption>Single-threaded in Async Programming model</figcaption></figure><h4>Multi-threaded in Async Programming model</h4><p>Tasks are interleaved as well, you can start a task in thread 1 and complete it in thread 2, so on and so forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*tGeCQJ9AZBg1J9hpyY_-Mw.png" /><figcaption>Multi-threaded in Async Programming model</figcaption></figure><blockquote>Reference: <a href="https://codewala.net/2015/07/29/concurrency-vs-multi-threading-vs-asynchronous-programming-explained/">single-threaded-multi-threaded</a></blockquote><h3>Async JavaScript</h3><p>We have mentioned that JavaScript is a single-threaded language, it means that it can only execute one task at a time, but if you remember the Day 14, we have mentioned a crucial concept — <strong>Event Loop</strong>, let’s review it.</p><h4>Event Loop</h4><p>Event loop is a mechanism that allows JavaScript to handle asynchronous events by offloading tasks to the browser’s Web APIs and executing them in the background.</p><p>Imagine that there are three bookers, one is to track every task, we called it Call Stack, one is to track tasks that are related to Web APIs, specifically setTimeout, setInterval or I/O, etc, we called it Macrotask Queue, sometimes we call it Task Queue or Callback Queue, the last one is to track tasks that are related to Promise, then, catch, finally, etc, we called it Microtask Queue.</p><p>When the function is called, it will be pushed to the Call Stack, when the function is executed, it will be popped from the Call Stack, simple as that, but when the function is related to Web APIs, it will be pushed to the Call Stack first then pushed into Web API, then move to Macrotask Queue or Microtask Queue.</p><p>Event Loopis the coordinator that will check if theCall Stackis empty, if it&#39;s empty then it will make sure that theMicrotask Queueis executed before theMacrotask Queue.</p><h3>Promise</h3><p>Promise is a built-in object in JavaScript, it represents the eventual completion (or failure) of an asynchronous operation and its resulting value.</p><p>It will return an object that has three states: pending, fulfilled, and rejected.</p><ul><li>pending: Initial state, neither fulfilled nor rejected.</li><li>fulfilled: The operation was completed successfully.</li><li>rejected: The operation failed.</li></ul><p>You may head of resolved, resolved means that the promise is settled or &quot;locked-in&quot; to match the eventual state of the promise, as it can be either fulfilled or rejected.</p><h4>Chaining</h4><p>You must have read or heard about a term — Callback Hell, it is a term that describes the situation where we have multiple callbacks that are nested inside each other, it is hard to read and maintain, like image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*e7QF674DVRmnJ6tROiA8YQ.png" /><figcaption>Callback Hell</figcaption></figure><h4>then, catch, finally</h4><p>In order to avoid the Callback Hell, we can use then to handle the result of the Promise.</p><pre>// Not using arrow function<br>doSomething()<br>  .then(function (result) {<br>    return doSomethingElse(result);<br>  })<br>  .then(function (result) {<br>    return doSomethingElse(result);<br>  });<br><br>// Using arrow function<br>doSomething()<br>  .then((result) =&gt; doSomethingElse(result))<br>  .then((result) =&gt; doSomethingElse(result));</pre><p>Usually we use then to handle the result of the Promise, but if the Promise is rejected, we can use catch to handle the error, finally is used to handle the result of the Promise, whether it is fulfilled or rejected.</p><h3>Promise concurrency</h3><h4>what is concurrency?</h4><p>Concurrency means processing multiple requests out of order or simultaneously, without affecting the final outcome, it’s about dealing with things at once, but not necessarily doing them at the same time.</p><ul><li><strong>Simultaneous vs. Interleaved Execution:</strong> <br>Concurrency does not necessarily mean things happen at the exact same moment, it can switching between tasks.</li><li><strong>Parallelism vs. Concurrency: </strong><br>Parallelism is about doing multiple things at the same time, while concurrency is about dealing multiple things at once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*WPCm96mCxOniT4qFwImsvA.png" /><figcaption>concurrency</figcaption></figure><h4>Promise.all()</h4><p>This will handel multiple promises at once, it will return a single promise that resolves when all of <strong>the promises in the array</strong> have resolved, and it will reject if any of the promises in the array reject.</p><pre>Promise.all([promise1, promise2, promise3])<br>  .then((values) =&gt; {<br>    console.log(values);<br>  })<br>  .catch((error) =&gt; {<br>    console.error(error);<br>  });</pre><h4>Promise.allSettled()</h4><p>Can be used when need to handle multiple promises at once, but don’t care about the result of the promises.</p><h4>Promise.race()</h4><p>Settles when any of the promises settles, fulfills when any of the promises fulfilled; rejected when any of the promises rejected.</p><h4>Promise.any()</h4><p>Fulfilled when any of the promises fulfilled; rejected when any of the promises rejected.</p><p>Methods above take an iterable of promises and return a new promise.</p><h3>async and await</h3><p>Basically async and await are syntactic sugar for Promise, it is more readable and easier to use.</p><p>Let’s compare the following code using Promise and async and await.</p><pre>// Using promise<br><br>const fetchData = () =&gt; {<br>  fetch(&quot;some.api.com&quot;)<br>    .then((res) =&gt; res.json())<br>    .then((data) =&gt; {<br>      console.log(data);<br>    });<br>    .catch((error) =&gt; {<br>      console.error(&quot;Error&quot;, error)<br>    })<br>}</pre><pre>// Using async await<br>const fetchData = async () =&gt; {<br>  try {<br>    const res = await fetch(&quot;some.api.com&quot;);<br>    const data = await res.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(&quot;Error&quot;, error);<br>  }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fcbad6cd1bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 14: Event Loop]]></title>
            <link>https://medium.com/@shan32157/day-14-event-loop-9d91107bf5bb?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d91107bf5bb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 04:21:55 GMT</pubDate>
            <atom:updated>2024-07-16T04:21:55.061Z</atom:updated>
            <content:encoded><![CDATA[<h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*zTgT6OBZ8Almg__zFfySkg.png" /><figcaption>Day 14: Event Loop</figcaption></figure><h3>What is Event Loop?</h3><p>Before we jump into what is Event Loop, let’s review some of the basic, but important concepts in JavaScript.</p><p>JavaScript is a <strong>single-thread</strong> language, it means JavaScript can do one thing at a time, It can’t do multiple things at the same time.</p><p>But sometimes we need to do multiple things at the same time, for example when we make an API call, we don’t want to wait for the response, we want to continue executing the code, and when the response is ready, we want to handle it. This is where the Event Loop comes into play.</p><h4>JavaScript Runtime Model</h4><p>JavaScript runtime model consists of the following components:</p><h4><strong>Call Stack</strong>:</h4><ul><li>Single-threaded execution of code.</li><li>Keeps track of function calls.</li><li>Last In First Out (LIFO) data structure.</li></ul><h4><strong>Heap</strong>:</h4><ul><li>Unstructured memory allocation.</li><li>Where Object are stored.</li></ul><h4><strong>Queue</strong>:</h4><ul><li><strong>Microtask Queue:</strong><br>- Has higher priority than the macrotask queue.<br>- Handles promises, mutation observer, for example Promise.then().</li><li><strong>Macrotask Queue or Task queue or Callback Queue</strong> (I’ll use Macrotask queue as it’s more precise):<br>- Handles events, setTimeout, setInterval, I/O operations, for example setTimeout(), setInterval(), fetch(), DOM events.</li></ul><h4><strong>Event Loop</strong>:</h4><ul><li>Continuously checks if the call stack is empty.</li><li>Moves callback from the event queue to the call stack when it’s empty.</li></ul><h4><strong>Web APIs (in browsers)</strong> or <strong>Node APIs (in Node.js)</strong>:</h4><ul><li>Provides additional functionalities.</li><li>Handle asynchronous operations.</li></ul><h3>How does Event Loop work?</h3><p>The Event Loop is a mechanism that makes JavaScript non-blocking. It allows JavaScript to perform multiple tasks without waiting for the completion of each task, think of it as a task scheduler, it schedules tasks to be executed in the future.</p><p>Essentially, the Event Loop continuously checks if the call stack is empty, then it will check if there’s a task in the microtask queue, if there is, it will move the task to the call stack, if not, it will check the macrotask queue, if there’s a task in the macrotask queue, it will move the task to the call stack.</p><p>Let’s take a diagram to understand how the Event Loop works and how it handles the macrotasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wQKxHeQ1gZpOjFciO6U4w.png" /><figcaption>macrotask</figcaption></figure><ol><li>JavaScript runtime starts reading the code, and create a global execution context, and push it to the call stack, in this stage, think of main() is a function that is being executed.</li><li>The first line of code is console.log(&#39;Start&#39;), this will be pushed to the call stack, and it will be executed immediately, one it&#39;s done, it will be popped out of the call stack.</li><li>The second line of code is a setTimeOut(), it will be pushed to the call stack as well, but then it will be moved to the Web APIs, and registered a timer. (See image below)</li><li>he last time of code is console.log(&#39;End&#39;), same as the first line, it will<br>be pushed to the call stack, and it will be executed immediately, one it&#39;s done, it will be popped out of the call stack.</li><li>After 0 seconds, the timer is done, the callback function of the setTimeout() will be moved to the macrotask queue.</li><li>The Event Loop will check if the call stack is empty, then it will check the macrotask queue, if there’s a task in the macrotask queue, it will move the task to the call stack.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*o3jDCL9h2Ig-A7qdi2sMbA.png" /><figcaption>Register a timer</figcaption></figure><p>This is a diagram to show how the Event Loop works and how it handles the microtasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZJhk0vMlWC2fjwyhUP4Zg.png" /><figcaption>microtask</figcaption></figure><p>When there’re microtasks and macrotasks, the Event Loop will always handle the microtasks first, then it will handle the macrotasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8sImx861urCAEVX66VQ_w.png" /><figcaption>Microtask and macrotask</figcaption></figure><h3>Conclusion</h3><ul><li>JavaScript is a single-threaded language, it can do one thing at a time, but thanks to the Event Loop, it can handle multiple tasks without waiting for the completion of each task.</li><li>There’re two types of tasks, microtasks and macrotasks, the Event Loop will always handle the microtasks first, then it will handle the macrotasks.<br>- <strong>Microtasks</strong>: promises, mutation observer, for example Promise.then().<br>- <strong>Macrotasks</strong>: events, setTimeout, setInterval, I/O operations, for example setTimeout(), setInterval(), fetch(), DOM events.</li><li>The Event Loop continuously checks if the call stack is empty, then it will check if there’s a task in the microtask queue, if there is, it will move the task to the call stack, if not, it will check the macrotask queue, if there’s a task in the macrotask queue, it will move the task to the call stack.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d91107bf5bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 5: Introduction to Networking]]></title>
            <link>https://medium.com/@shan32157/day-5-introduction-to-networking-e63b9d6c862d?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e63b9d6c862d</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 01:31:35 GMT</pubDate>
            <atom:updated>2024-07-15T01:31:35.993Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Structures &amp; Algorithms + bit of CS Fundamentals in 30 days 🥶</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*9eMjgDHBcXW9eKvpVsXrFA.png" /><figcaption>Day 5: Introduction to Networking</figcaption></figure><h3>What is Computer Networking?</h3><p>Computer Networking refers to interconnected computing that can exchange data and resources with each other, below are some of the key concepts of computer networking:</p><h3>Network Types:</h3><ul><li><strong>Local Area Network (LAN)</strong>: A network that spans a relatively small area.</li><li><strong>Wide Area Network (WAN)</strong>: A network that covers a broad area, often a country or continent, and can include multiple LAN.</li><li><strong>Personal Area Network (PAN)</strong>: A network for personal devices within a short range, such a Bluetooth connections.</li><li><strong>Metropolitan Area Network (WAN)</strong>: A network that covers a city or a lager campus.</li></ul><h3>Network Topologies:</h3><ul><li><strong>Bus</strong>: All devices are connected to a single central cable.</li><li><strong>Star</strong>: All devices are connected to a central hub.</li><li><strong>Ring</strong>: Devices are connected in a circular configuration.</li><li><strong>Mesh</strong>: Devices are interconnected, providing multiple paths for data to travel.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSnmCAsacUqUkQFnqFhMrQ.png" /><figcaption>Network Topologies (source: Wiki)</figcaption></figure><h3>Network protocols</h3><ul><li><strong>TCP/IP</strong>: The fundamental suite of protocols for the interne, including Transmission Control Protocol (TCP) and Internet Protocol (IP)</li><li><strong>HTTP/HTTPs</strong>: Protocols for transferring hypertext over the web.</li><li><strong>FTP</strong>: Protocol for file transfer.</li><li><strong>SMTP</strong>: Protocol for sending emails.</li><li><strong>DNS</strong>: System for translating human-readable domain names into IP address.</li></ul><h3>Network Hardware</h3><ul><li><strong>Router</strong>: A device that forwards data packets between computer networks.</li><li><strong>Switch</strong>: A device that connects devices within a LAN and forwards data to the correct destination.</li><li><strong>Modem</strong>: A device that modulates and demodulates signals for communication over telephone lines or cable systems.</li><li><strong>Access Point</strong>: A device that allows wireless devices to connect to a wired network.</li></ul><h3>IP Addressing</h3><ul><li><strong>IPv4</strong>: Uses <strong>32-bit</strong> addresses, providing about 4.3 billion unique addresses.</li><li><strong>IPv6</strong>: Uses <strong>128-bit</strong> addresses, providing a vastly larger address space.</li></ul><h3>Network Services</h3><ul><li><strong>DHCP</strong>: Dynamic Host Configuration Protocol, which assigns IP addresses to devices on a network.</li><li><strong>DNS</strong>: Domain Name System, which translates domain names to IP addresses.</li></ul><h3>Network Security</h3><ul><li><strong>Firewalls</strong>: Systems that monitor and control incoming and outgoing network traffic based on predetermined security rules.</li><li><strong>Encryption</strong>: The process of encoding data to prevent unauthorized access.</li><li><strong>VPNs</strong>: Virtual Private Networks, which create secure connections over the internet.</li></ul><h3>Network Performance</h3><ul><li><strong>Bandwidth</strong>: The maximum rate of data transfer across a network.</li><li><strong>Latency</strong>: The time it takes for data to travel from the source to the destination.<br>- <strong>Processing Delay</strong>: Time it takes a router to process the packet header.<br>- <strong>Queuing Delay</strong>: Time a packet spends in a router’s queue.<br>- <strong>Transmission Delay</strong>: Time it takes to push the packet’s bits onto the link.<br>- <strong>Propagation Delay</strong>: Time for a signal to propagate through the media.</li><li><strong>Ping</strong>: A network utility that tests the reachability of a host on an IP network.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e63b9d6c862d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Postfix vs. Prefix]]></title>
            <link>https://medium.com/@shan32157/javascript-postfix-vs-prefix-cb9ae24fbfcd?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9ae24fbfcd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[increments]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 09:34:58 GMT</pubDate>
            <atom:updated>2024-07-12T09:34:58.825Z</atom:updated>
            <content:encoded><![CDATA[<h4>Interesting part of JavaScript 👻</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xeqkJsLvFcpoWxES86ktIw.png" /></figure><p>Recently, I started solving some interview questions, and one of the questions was to create a counter with several actions. Here is the task description.</p><pre>Implement a function makeCounter that accepts an optional integer value <br>(defaults to 0) and returns an object that contains the following methods:<br><br>get(): returns the current value.<br>increment(): increments the current value and returns it.<br>decrement(): decrements the current value and returns it.<br>reset(): resets the current value to the initial value.</pre><p>At the first glance, I was like…okay, this sould be easy for me to solve, but I did not pass the task.</p><p>This was my approach:</p><pre>interface Counter {<br>  get: () =&gt; number;<br>  increment: () =&gt; number;<br>  decrement: () =&gt; number;<br>  reset: () =&gt; number;<br>}<br><br>function makeCounter(initialValue: number = 0):Counter {<br>  return {<br>    get: () =&gt; initialValue,<br>    increment: () =&gt; initialValue++,<br>    decrement: () =&gt; initialValue--,<br>    reset: () =&gt; initialValue,<br>  }<br>}<br><br>const counter = makeCounter(1);<br><br>console.log(counter.get())<br>console.log(counter.increment())<br>console.log(counter.increment())<br>console.log(counter.reset())</pre><p>Can you guess the result?</p><p>The result is 1, 1, 2, 3 , I thought it should be 1, 2, 3, 1 , but why?</p><h3>Blind spots</h3><ul><li>The makeCounter function accepts a parameter with a default value of 0. In my approach, I used the parameter directly, which caused some bugs. I should have created another variable and assigned the value of initialValue to it to help keep track of the state.</li><li>The initialValue++ is a postfix increment operator, which returns the value before incrementing. Therefore, when I executed counter.increment() to be 2, it had the previous value of initialValue, which was 1, and so on. Check the diagram below for more clarity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3bdFBw020gXp0Ls8f8L5Q.png" /><figcaption>diagram-1</figcaption></figure><h3>Solution</h3><ul><li>Create a variable to keep track of the latest state.</li><li>Use prefix increment operator to make sure getting the updated result.</li></ul><pre>interface Counter {<br>  get: () =&gt; number;<br>  increment: () =&gt; number;<br>  decrement: () =&gt; number;<br>  reset: () =&gt; number;<br>}<br><br>function makeCounter(initialValue: number = 0):Counter {<br>  let value = initialValue;<br>  return {<br>    get: () =&gt; value,<br>    increment: () =&gt; ++value,<br>    decrement: () =&gt; ++value,<br>    reset: () =&gt; ( value = initialValue),<br>  }<br>}<br><br>const counter = makeCounter(1);<br><br>console.log(counter.get())<br>console.log(counter.increment())<br>console.log(counter.increment())<br>console.log(counter.reset())</pre><p>Here is the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBLxH2z8QQlDuoDzWQGWvw.png" /><figcaption>diagram-2</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9ae24fbfcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 13 : Functions part 4(Call Stack)]]></title>
            <link>https://medium.com/@shan32157/day-13-functions-part-4-call-stack-4bbc2ccbb51e?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbc2ccbb51e</guid>
            <category><![CDATA[call-stack]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 03:32:03 GMT</pubDate>
            <atom:updated>2024-07-12T03:32:03.896Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 13 : Functions part 4(Call Stack)</h3><h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*zSWZ_Kp-DGd_wyRpfMazVQ.png" /><figcaption>Day 13 : Functions part 4(Call Stack)</figcaption></figure><h3>What is stack?</h3><p>Stack is a data structure that follows the role of <strong>Last In, First Out (LIFO)</strong>. It means that the last element added to the stack will be the first one to be removed.</p><p>Think of a stack of a pile of books, the last book you put on the stack will be the first one you take off.</p><p>In JavaScript, the stack is used to keep track of function calls. When a function is called, it is added to the top of the stack. When the function returns, it is removed from the stack.</p><h3>The first call stack in JavaScript</h3><p>When we execute a script, JS engine creates a <strong>global context</strong>, also indicated by <strong>main()</strong> or <strong>global()</strong> and pushes it on the top of the call stack. Then if there’re other functions to be executed, they will be pushed on the top of the stack, when we talk about main() or global(), we often refer to the global execution context, it contains:</p><ul><li>Global Object (window in the browser, global in Node.js), this is why we can access these objects without declaring them, for example, console.log(), setTimeout(), Math, window.location, etc.</li><li>All the functions and variables declared in the global scope.</li><li>this keyword, which refers to the global object.</li></ul><p>What about a nested function? Let’s say we have 2 layers of functions, is this going to be 2 stacks or 1 stack?</p><blockquote>JavaScript Call Stack is a single-threaded, synchronous execution model, we can have different execution contexts based on the scope, but we only have 1 stack to keep track of all the function calls.</blockquote><p>Let’s see an example:</p><pre>function func_1() {<br>  console.log(&quot;Inside func_1&quot;);<br>  func_2();<br>  console.log(&quot;existing func_1&quot;);<br>}<br><br>function func_2() {<br>  console.log(&quot;Inside func_2&quot;);<br>  func_3();<br>  console.log(&quot;existing func_2&quot;);<br>}<br><br>function fun_3() {<br>  console.log(&quot;Inside func_3&quot;);<br>  console.log(&quot;existing func_3&quot;);<br>}<br><br>console.log(&quot;Starts Here&quot;);<br>func_1();<br>console.log(&quot;End Here&quot;);</pre><p>Let’s walk through the code:</p><ol><li>JavaScript is a single thread language, it reads code from the top to the bottom, the engine creates a global execution context to store all the function in the memory.</li><li>The first execution is the console.log(&#39;Starts Here&#39;), it is a <strong>Web API</strong>, so the first thing we&#39;ve got it the string of Starts Here</li><li>The second line func_1(), it is a function call, so the engine will push the func_1 on the top of the stack, this would be the first stack.</li><li>When we execute the func_1(), everything is going to inside this functional execution context, it will execute the console.log(&quot;Inside func_1&quot;), then it will call the func_2(), so the func_2() will be pushed on the top of the stack.</li><li>The func_2() will execute the console.log(&quot;Inside func_2&quot;), then it will call the func_3(), so the func_3() will be pushed on the top of the stack.</li><li>The func_3() will execute the console.log(&quot;Inside func_3&quot;), then it will return to the func_2(), so the func_3() will be removed from the stack.</li><li>The func_2() will execute the console.log(&quot;existing func_2&quot;), then it will return to the func_1(), so the func_2() will be removed from the stack.</li><li>The func_1() will execute the console.log(&quot;existing func_1&quot;), then it will return to the global execution context, so the func_1() will be removed from the stack.</li><li>The last line console.log(&quot;End Here&quot;), it is a <strong>Web API</strong>, so the last thing we&#39;ve got it the string of End Here.</li></ol><p>So the result would be:</p><pre>Starts Here<br>Inside func_1<br>Inside func_2<br>Inside func_3<br>existing func_3<br>existing func_2<br>existing func_1<br>End Here</pre><p>Hard to read? No worries, let’s see this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOWR9GFjA45g3nNT-w5T1Q.png" /><figcaption>call stack diagram from code above</figcaption></figure><p>Here is the video.</p><p><a href="https://drive.google.com/file/d/1L38jBTxpZrTkLAcSIyvlKIbU7vR-AM0a/view?usp=sharing">callstack.mov</a></p><h3>Stack Overflow</h3><p>The stack has a limited size, if we have too many function calls, it will cause a <strong>stack overflow</strong> error, for instance, you have a recursive function that doesn’t have a base case, it will keep calling itself until the stack is full.</p><pre>function callMyself() {<br>  callMyself();<br>}</pre><p>If you run this code, you will get a <strong>RangeError: Maximum call stack size exceeded</strong>. If you have used react for a while, you might have seen this error before, it happens when using useEffect without a dependency array, it will cause an infinite loop.</p><h3><strong>Tools that can help you to debug the call stack</strong></h3><ul><li>Chrome DevTools: You can use the <strong>Sources</strong> tab to debug the call stack, you can set breakpoints, step through the code, and see the call stack.</li><li><a href="https://www.jsv9000.app/">jsv900</a></li><li><a href="http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D">loupe</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbc2ccbb51e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 4: Calculating Bit Depths]]></title>
            <link>https://medium.com/@shan32157/day-4-calculating-bit-depths-053139091b5e?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/053139091b5e</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[fundamentals]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 00:50:32 GMT</pubDate>
            <atom:updated>2024-07-10T00:50:32.058Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Structures &amp; Algorithms + bit of CS Fundamentals in 30 days 🥶</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*kf5lxf1IoUoxUhgIuPrWrg.png" /><figcaption>Data Structures &amp; Algorithms + bit of CS Fundamentals in 30 days: Day 4 Calculating Bit depths</figcaption></figure><h3>What is Bit Depth?</h3><p>Bit depth is the number of bits used to represent each sample in a digital audio or image files. Bit depths determine the number of possible values that can be assigned to each sample. The higher the bit depth, the more accurate the representation of the original signal.</p><h3>Application of Bit Depth in Images</h3><p>In image, bit depth typically refers to the number of bits used for each pixel’s color information, common bit depths include:</p><ul><li>1-bit: 2 colors (black and white)</li><li>8-bit: 256 colors (2⁸)</li><li>24-bit: 16.7 million colors (2²⁴), usually divided into 8 bits:<br>- 8 bits for red<br>- 8 bits for green<br>- 8 bits for blue</li></ul><h4>Formula for Calculating Bit Depth in Images</h4><p>The formula for calculating bit depth in images is:</p><pre>Number of Colors = 2^Bit Depth</pre><p>For example, for a 24-bit image:</p><pre>Number of Colors = 2^24 = 16,777,216</pre><h3>Application of Bit Depth in Audio</h3><p>In audio, bit depth refers to the number of bits used to represent each sample in a digital audio file. Common bit depths include:</p><ul><li>8-bit: 256 possible values (2⁸)</li><li>16-bit: 65,536 possible values (2¹⁶)</li><li>24-bit: 16.7 million possible values (2²⁴)</li></ul><p>Formula is the same as for images.</p><h3>Importance of Bit Depth</h3><p>There’re two main reasons why bit depth is important:</p><ul><li><strong>Image Quality</strong>: Higher bit depth images can represent more colors, showing smoother gradients and more accurate color representation.</li><li><strong>Audio Quality</strong>: Higher bit depth audio files can capture a greater dynamic range, providing more sound details and less distortion.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=053139091b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 12 : Functions Part 3 (IIFE)]]></title>
            <link>https://medium.com/@shan32157/day-12-functions-part-3-iife-e8880def6810?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8880def6810</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[iife]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 06:57:58 GMT</pubDate>
            <atom:updated>2024-07-01T06:57:58.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 12 : Functions Part 3 (IIFE)</h3><h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*YMiwLY6RLap67sDZCy4BTQ.png" /><figcaption>JS Funmamentals in 30 days</figcaption></figure><h3>What is IIFE?</h3><p>IIFE (pronouns as “iffy”) refers to <strong>Immediately Invoked Function Expression</strong>, it’s a function that runs as soon as it’s defined.</p><p>It is also called a <strong>Self-Executing Anonymous Function</strong>, it contains two major parts:</p><ol><li>The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.</li><li>The second part creates the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.</li></ol><p>Consider the code snippet below and let’s break it down:</p><pre>(function () {<br>  console.log(&quot;This function is executed immediately!&quot;);<br>})();</pre><ul><li>The anonymous function is defined and wrapped within the Grouping Operator ().</li><li>The () at the end of the function definition calls the function immediately.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IP-LFoaIDA1RucM_XjJ5yA.png" /></figure><h4>Several ways to write IIFE</h4><ul><li>Using arrow function.</li></ul><pre>(() =&gt; {<br>  console.log(&quot;This function is executed immediately!&quot;);<br>})();</pre><ul><li>Using keyword function.</li></ul><pre>(function () {<br>  console.log(&quot;This function is executed immediately!&quot;);<br>})();</pre><ul><li>Using ! operator.</li></ul><pre>!(function () {<br>  console.log(&quot;This function is executed immediately!&quot;);<br>})();</pre><p>This writing style is primarily used to ensure that the function is treated as an expression rather than a declaration, you might have seen people using !, +, -, ~ operators to achieve the same result, but this is not recommended because it can be confusing and not intuitive.</p><h3>Use Cases of IIFE</h3><h4>Does not pollute the global scope</h4><p>In normal situation or building a relatively small project, it is okay to declare variables in the global scope, but when working on a large project, it could cause problems like name collision, overwriting variables, and so on.</p><p>IIFE helps to prevent this by creating a private scope for the variables declared within it and when the function is executed, the variables are destroyed.</p><pre>// Not using IIFE<br><br>const name = &quot;John&quot;;<br><br>function sayHello() {<br>  console.log(`Hello, ${name}`);<br>}<br><br>// Using IIFE<br>(() =&gt; {<br>  const name = &quot;John&quot;;<br>  const sayHello = () =&gt; {<br>    console.log(`Hello, ${name}`);<br>  };<br>  console.log(&quot;Inside IIFE&quot;, name);<br>  sayHello();<br>})();</pre><p>In second example, IIFE will be executed immediately once the script is loaded and the variables declared within it will be destroyed after the function is executed, so if we try to invoke the sayHello function and name variable outside the IIFE, it will throw an error, see the code below:</p><pre>(() =&gt; {<br>  const name = &quot;John&quot;;<br>  const sayHello = () =&gt; {<br>    console.log(`Hello, ${name}`);<br>  };<br>  console.log(&quot;Inside IIFE&quot;, name); // Output: John<br>  sayHello(); // Output: Hello, John<br>})();<br><br>console.log(&quot;Outside IIFE&quot;, name); // Error<br>sayHello(); // Error</pre><h4>Create private variables and closures</h4><p>Let’s review the definition of closure:</p><blockquote><em>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. — MDN Web Docs</em></blockquote><p>Let’s see the following code:</p><pre>// code might be a bit different as the image below, but it works in the same way.<br>const counter = (() =&gt; {<br>  let count = 0;<br>  const increment = () =&gt; {<br>    count++;<br>    return count;<br>  };<br>  const decrement = () =&gt; {<br>    count--;<br>    return count;<br>  };<br>  return {<br>    increment,<br>    decrement,<br>  };<br>})();<br><br>console.log(counter.increment()); // Output: 1<br>console.log(counter.decrement()); // Output: 0<br>console.log(count); // Error</pre><p>Let’s break down the code above:</p><p>We declare a function expression called counter, inside the function, we declare a variable called count, and return an object with two methods, increment and decrement.</p><p>When we invoke the counter.increment() method, it increments the count variable by 1, and when we invoke the counter.decrement() method, it decrements the count variable by 1.</p><p>Why can we access the count variable? Think about when we execute counter function, we sort of create a shield from counter to the last curly brace, we can&#39;t access count outside the function because the scope, but when we try to access the increment and decrement methods, these two methods have access to the count variable because they are within the same shield.</p><p>Inside increment, it tried to look for count variable, it couldn&#39;t find it in its scope, so it went up to the parent scope which is the counter function and found the count variable and plus 1 to it, same process for decrement method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9MgGLdV2t_QWqg3h6jeHw.png" /></figure><h4>Module Pattern</h4><p>We can encapsulate our code using IIFE to create a module pattern, this is a design pattern used for creating a set of related methods and variables, together with the principle of information hiding, encapsulation, and organization.</p><p>For example, we might have seen something like this:</p><pre>const add = (x, y) =&gt; {<br>  const result = x + y;<br>  return result;<br>};<br><br>const subtract = (x, y) =&gt; {<br>  const result = x - y;<br>  return result;<br>};<br><br>const multiply = (x, y) =&gt; {<br>  const result = x * y;<br>  return result;<br>};<br><br>export { add, subtract, multiply };</pre><p>But we can refactor the code above using IIFE to create a module pattern like this:</p><pre>const CalculateMath = (() =&gt; {<br>  return {<br>    add: (x, y) =&gt; {<br>      const result = x + y;<br>      return result;<br>    },<br>    subtract: (x, y) =&gt; {<br>      const result = x - y;<br>      return result;<br>    },<br>    multiply: (x, y) =&gt; {<br>      const result = x * y;<br>      return result;<br>    },<br>  };<br>})();<br><br>export default CalculateMath;</pre><p>And we can use it like this:</p><pre>import CalculateMath from &quot;./CalculateMath.js&quot;;<br><br>console.log(CalculateMath.add(2, 3)); // Output: 5<br>console.log(CalculateMath.subtract(5, 3)); // Output: 2<br>console.log(CalculateMath.multiply(2, 3)); // Output: 6</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8880def6810" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3: Day 3 Data Compression]]></title>
            <link>https://medium.com/@shan32157/day-3-day-3-data-compression-aa0eabcbb2fd?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0eabcbb2fd</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[fundamentals]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 08:41:42 GMT</pubDate>
            <atom:updated>2024-06-20T08:41:42.253Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Structures &amp; Algorithms + bit of CS Fundamentals in 30 days 🥶</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*LfCNK4SnEMBdB2vnHaevGg.png" /><figcaption>Computer Science + data structures &amp; Algorithms fundamentals in 30 days or more</figcaption></figure><h3>What is Data Compression?</h3><p>It is a process of encoding information using fewer bits than the original representation, in short, it is a process of reducing the size of data.</p><h3>Types of Data Compression</h3><ul><li>Lossless Compression</li><li>Lossy Compression</li></ul><h4>Lossless Compression</h4><p>It allows the original data to be compressed without losing any information, and it is reversible due to most of the data exhibits <strong>statistical redundancy</strong>.</p><p>Statistical redundancy means extra or unnecessary data that can be removed without loss of information. For example in the string “AAAAABBBBCCCCDDDD”, the redundancy is the repetition of the same character, so it can be compressed to “A<em>5B</em>4C<em>4D</em>4”, not only we save space, we also maintain the original data.</p><p>Techniques used in Lossless Compression:</p><ul><li>Huffman Coding</li><li>Arithmetic Coding</li></ul><h4>Lossy Compression (Also called Irreversible Compression)</h4><p>It is used to reduce data size for storing, handling and transmitting content. Lossy compression is commonly used to compress multimedia data (audio, video, and images), especially in streaming media and <strong>internet telephony</strong> (Voice over Internet Protocol or IP telephony).</p><h3>Data compression techniques that are related to frontend development</h3><p>In order to improve the performance of a website, data compression plays a crucial role, it helps to reduce the size of the data that is being transferred between the server and the client, below are common ways to improve the performance of a website.</p><h4>Image Compression</h4><p>Images are the most common type of data, we can try to reduce image size, lower the quality of the image or change the format of the image, check <a href="https://web.dev/learn/performance/image-performance">Web.dev — Image Performance</a> for more information.</p><ul><li>Lossless Compression: It describes a pixel based on the difference from its neighboring pixels, it is used in PNG, GIF, WebP and AVIF.</li><li>Lossy Compression: It’s effective on high-density images with lots of noise and colors, but less effective with imagery containing sharp edges such as line art or text, this can be applied to JPEG, WebP and AVIF.</li><li>Tools that help to compress images:<br>- <a href="https://tinypng.com/">TinyPNG</a><br>- <a href="https://imageoptim.com/">ImageOptim</a><br>- <a href="https://squoosh.app/">Squoosh</a><br>- <a href="https://compressor.io/">Compressor.io</a></li></ul><h4>File Compression</h4><p>You may heard of <strong>Minification</strong>, it is a process of removing unnecessary characters from the source code without changing its functionality, it helps to reduce the size of the file, and optimize the performance of the website.</p><p><strong>Tree Shaking</strong> is another technique that helps to remove unused code during the build process, we can use tools like Webpack, Rollup to achieve this.</p><p>We can use other techniques like <strong>Code Splitting</strong>, <strong>Lazy Loading</strong> to improve the performance of the website.</p><p>In modern frameworks like React, Angular, Vue, they have built-in tools to help developers to optimize the performance of the website.</p><h4>HTTP Compression</h4><p>HTTP compression is a capability that can be built into web servers and web clients to improve transfer speed and bandwidth utilization, it is supported by most of the modern browsers and servers.</p><p>Checkout MDN Web Docs for more information on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Compression">HTTP Compression</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0eabcbb2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 11 : Functions part 2 (Higher Order Functions]]></title>
            <link>https://medium.com/@shan32157/day-11-functions-part-2-higher-order-functions-f81af5fa8ea8?source=rss-4ab69d535ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f81af5fa8ea8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Shan]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 08:03:14 GMT</pubDate>
            <atom:updated>2024-06-20T01:32:00.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 11 : Functions part 2 (Higher Order Functions</h3><h4>JS Fundamentals in 30 days 🫨</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*_LV6xINcjjkc5WSYpPcNcQ.png" /><figcaption>JS fundamentals in 30 days</figcaption></figure><h3>What is a Higher Order Function?</h3><p>In computer science and mathematics, a higher-order function (HOF) is a function that does at least one of the following:</p><ol><li>Takes one or more functions as arguments.</li><li>Returns a function as its result.</li></ol><h4>Accepting functions as arguments</h4><p>This allows for dynamic behavior, as functions can be passed as arguments to other functions.</p><pre>function greeting() {<br>  return `Hello, ${name}`;<br>}<br><br>function user(name, callback) {<br>  return callback(name);<br>}<br><br>console.log(user(&quot;Andy&quot;, greeting)); // Hello, Andy</pre><p>Let’s walk through the code snippet above:</p><ul><li>We created a function greeting that return a string Hello, ${name}.</li><li>We created a function user that takes two arguments, name and callback, and the callback here is a function.</li><li>The user function returns the result of calling the callback function with the name argument.</li><li>We passed Andy and the greeting function as arguments to the user function.</li><li>The user function calls the greeting function with the Andy argument and returns the result.</li></ul><h4>Returning a function</h4><pre>function multiplier(x) {<br>  return function (y) {<br>    return x * y;<br>  };<br>}<br><br>const double = multiplier(2);<br><br>console.log(double(5)); // 10</pre><ul><li>We created a function multiplier that takes one argument x and returns a function that takes another argument y and returns the x * y.</li><li>We created a constant double that stores the result of calling the multiplier function with the argument 2.</li></ul><pre>const double = function (y) {<br>  return 2 * y;<br>};<br><br>double(5);</pre><ul><li>We called the double function with the argument 5 and it returns 10, like below:</li></ul><pre>function(5) {<br>  return 2 * 5;<br>}</pre><h3>Common Higher Order Functions in JavaScript</h3><ul><li>map()</li><li>filter()</li><li>reduce()</li><li>sort()</li></ul><h4>map()</h4><p>map() is a method of Array, it creates a new array with the results. It takes two parameters, a callbackFn and an optional thisArg, thisArg is a value to use as this when executing callbackFn.</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>// Using function expression<br>const doubled = numbers.map(function (number) {<br>  return number * 2;<br>});<br><br>// Using arrow function<br>const doubled = numbers.map((number) =&gt; number * 2);<br><br>console.log(doubled); // [2, 4, 6, 8, 10]</pre><p>The code above shows basic usage of the map() method, when you need to iterate over an array and modify each element in the array.</p><p>if somehow we need to <strong>access an object</strong>, we can use the second parameter of the map() method (thisArg), like below:</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const calculator = {<br>  multiplier: 2,<br>  multiply(number) {<br>    return number * this.multiplier;<br>  },<br>};<br><br>const doubled = numbers.map(calculator.multiply, calculator);<br>console.log(doubled); // [2, 4, 6, 8, 10]</pre><h4>filter()</h4><p>filter() method creates a <strong>shallow copy</strong> of a portion of a given array.</p><p>Same as map(), it takes two parameters, a callbackFn and an optional thisArg.</p><p>first of all, let’s talk about what is a <strong>shallow copy</strong> in a simple way, we will dive into it in the next section.</p><ul><li>The opposite of a shallow copy is a deep copy.</li><li>A shallow copy of an object means it shares the same properties as the original object.</li><li>When we change either the source of the copy or the copy itself, the changes are reflected in both objects.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br><br>// Using function expression<br>const evenNumbers = numbers.filter(function (number) {<br>  return number % 2 === 0;<br>});<br><br>// Using arrow function<br>const evenNumbers = numbers.filter((number) =&gt; number % 2 === 0);<br><br>console.log(evenNumbers); // [2, 4]</pre><p>With thisArg:</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const calculator = {<br>  divider: 2,<br>  isEven(number) {<br>    return number % this.divider === 0;<br>  },<br>};<br><br>const evenNumbers = numbers.filter(calculator.isEven, calculator);<br><br>console.log(evenNumbers); // [2, 4]</pre><h4>reduce()</h4><p>reduce() method executes a user-supplied &quot;reducer&quot; callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.</p><pre>const numbers = [1, 2, 3];<br>const initialVal = 0;<br><br>const sum = numbers.reduce(<br>  (accumulator, currentVal) =&gt; accumulator + currentVal,<br>  initialVal<br>);<br><br>console.log(sum); // 6</pre><p>Here is how reduce() works:</p><ul><li>First time:<br>- accumulator = initialVal = 0<br>- currentVal = numbers[0] = 1<br>- execute callback function: accumulator + currentVal = 0 + 1 = 1<br>- return 1 as the new accumulator value</li><li>Second time:<br>- accumulator = 1<br>- currentVal = numbers[1] = 2 <br>- execute callback function: accumulator + currentVal = 1 + 2 = 3 <br>- return 3 as the new accumulator value</li><li>Third time:<br>- accumulator = 3 <br>- currentVal = numbers[2] = 3 <br>- execute callback function: accumulator + currentVal = 3 + 3 = 6 <br>- return 6 as the new accumulator value<br>- no more elements in the array, return 6</li></ul><h4>sort()</h4><p>sort() is a method that sorts the elements of an array <strong>in place</strong> and returns the <strong>reference</strong> to the same and sorted array, the default sort order is ascending.</p><p><strong>What is in place?</strong></p><ul><li>It is an algorithm — in-place algorithm.</li><li>It operates directly on the input data structure without requiring extra space proportional to the input size.</li><li>The opposite of an in-place algorithm is an <strong>out-of-place</strong> algorithm.</li></ul><pre>const nums = [3, 6, 2, 5, 9];<br><br>nums.sort();<br><br>console.log(&quot;Ascending&quot;, nums); // [2, 3, 5, 6, 9]<br><br>const ascendingArr = nums.sort((a, b) =&gt; a - b);<br><br>console.log(&quot;Ascending&quot;, ascendingArr); // [2, 3, 5, 6, 9]<br><br>const descendingArr = nums.sort((a, b) =&gt; b - a);<br><br>console.log(&quot;Descending&quot;, descendingArr); // [9, 6, 5, 3, 2]</pre><p>The code above will mutate the original array, if you want to keep the original array unchanged, you can create a copy of the array and sort the copy.</p><pre>// Using toSorted() method, but it&#39;s not support in node.js yet.<br>// Try to use it in the browser console.<br>const numbers = [2, 7, 3, 1, 4];<br><br>const newNums = numbers.toSorted();<br><br>console.log(numbers); // [1, 2, 3, 4, 7]<br><br>console.log(numbers !== newNums); // true<br><br>// Using ...spread operator<br>const numbers = [2, 7, 3, 1, 4];<br><br>const newNums = [...numbers].sort();<br><br>console.log(newNums); // [1, 2, 3, 4, 7]<br><br>console.log(numbers !== newNums); // true</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f81af5fa8ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>