<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Sanjeev Sharma</title>
    <description>The latest articles on Forem by Sanjeev Sharma (@thesanjeevsharma).</description>
    <link>https://forem.com/thesanjeevsharma</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F338134%2F7fec21da-0b0b-450c-98ef-f8fa15d1fc06.jpg</url>
      <title>Forem: Sanjeev Sharma</title>
      <link>https://forem.com/thesanjeevsharma</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/thesanjeevsharma"/>
    <language>en</language>
    <item>
      <title>CORS, Preflight Requests, and Common Cross-Origin Issues</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Fri, 28 Feb 2025 19:44:07 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/cors-preflight-requests-and-common-cross-origin-issues-129n</link>
      <guid>https://forem.com/thesanjeevsharma/cors-preflight-requests-and-common-cross-origin-issues-129n</guid>
      <description>&lt;p&gt;If you've been developing web apps for a while, there's a 99% chance you've encountered a CORS issue at least once. If you're a beginner, you probably found a one-line fix by Googling the exact error and moved on with your task. Today, with AI tools, you don’t even have to leave your IDE to get a solution.&lt;/p&gt;

&lt;p&gt;But did you truly understand what the fix did? Why did the issue occur in the first place? If not, I promise that by the end of this post, you will.&lt;/p&gt;

&lt;p&gt;Let’s dive in! 💪&lt;/p&gt;




&lt;h2&gt;
  
  
  What is CORS?
&lt;/h2&gt;

&lt;p&gt;CORS, or &lt;em&gt;Cross-Origin Resource Sharing&lt;/em&gt;, is a browser mechanism that restricts frontend code from making cross-origin requests. It’s not an issue per se but a security feature designed to protect users and websites.&lt;/p&gt;

&lt;p&gt;The error you encounter typically occurs when your frontend and backend are deployed on separate domains (or subdomains).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzg21saf3uikecd3e676k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzg21saf3uikecd3e676k.png" alt="CORS" width="800" height="348"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above, &lt;code&gt;frontendcamp.in&lt;/code&gt; makes a request to &lt;code&gt;api.dev.to&lt;/code&gt;. If &lt;code&gt;api.dev.to&lt;/code&gt; doesn’t explicitly allow requests from other origins, the browser will block the request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do browsers do that?&lt;/strong&gt;&lt;br&gt;
Browsers enforce the SOP or &lt;em&gt;Same-Origin Policy&lt;/em&gt;, which dictates how a document or script from one origin can interact with resources on another. This prevents malicious websites from executing code on your site.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Two origins are considered the same if the &lt;code&gt;protocol&lt;/code&gt;, &lt;code&gt;port&lt;/code&gt; (if specified), and &lt;code&gt;host&lt;/code&gt; match.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;How to fix this issue?&lt;/strong&gt;&lt;br&gt;
To resolve this, the server must explicitly allow requests from the frontend’s origin.&lt;/p&gt;

&lt;p&gt;For example, in the illustration above, &lt;code&gt;api.dev.to&lt;/code&gt; should permit &lt;code&gt;www.frontendcamp.in&lt;/code&gt; to access its resources.&lt;/p&gt;

&lt;p&gt;This can done by adding the following response header.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Access-Control-Allow-Origin: https://www.frontendcamp.in
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This header informs the browser that &lt;code&gt;www.frontendcamp.in&lt;/code&gt; is authorized to access the resource.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Some developers use &lt;code&gt;*&lt;/code&gt; as the header value, allowing requests from any origin. Avoid this unless you have a valid reason for doing so.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;An alternate solution&lt;/strong&gt;&lt;br&gt;
You can’t always modify response headers. For instance, when requesting data from an external service, the above solution won’t work.&lt;/p&gt;

&lt;p&gt;In such cases, a proxy server can be used.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2e93b8cynir817vt4a54.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2e93b8cynir817vt4a54.png" alt="CORS with Proxy server" width="800" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This works because CORS is enforced only by browsers. With a proxy server in place, the browser perceives the request as originating from the same domain.&lt;/p&gt;


&lt;h2&gt;
  
  
  Preflight Requests
&lt;/h2&gt;

&lt;p&gt;A preflight request is a CORS request that the browser automatically sends before the actual request when a cross-origin request is not &lt;em&gt;simple&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;It uses the &lt;code&gt;OPTIONS&lt;/code&gt; method and includes up to three headers: &lt;code&gt;Access-Control-Request-Method&lt;/code&gt;, &lt;code&gt;Origin&lt;/code&gt;, and optionally, &lt;code&gt;Access-Control-Request-Headers&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What kind of requests are not considered &lt;em&gt;simple&lt;/em&gt;?&lt;/strong&gt;&lt;br&gt;
A request requires a preflight if it meets any of the following conditions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It uses an HTTP method other than &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, or &lt;code&gt;HEAD&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It includes custom headers, such as &lt;code&gt;Authorization&lt;/code&gt; or &lt;code&gt;X-Registered-With&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It sends data in formats other than &lt;code&gt;application/x-www-form-urlencoded&lt;/code&gt;, &lt;code&gt;multipart/form-data&lt;/code&gt;, or &lt;code&gt;text/plain&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example, if &lt;code&gt;frontendcamp.in&lt;/code&gt; makes a &lt;code&gt;DELETE&lt;/code&gt; request to &lt;code&gt;api.dev.to&lt;/code&gt;, the request flow would be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A preflight request is sent.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;OPTIONS /v1/posts/224
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: x-requested-with
Origin: https://frontendcamp.in
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;The server responds with the applicable CORS policy.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://frontendcamp.in
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, X-Registered-With
Access-Control-Max-Age: 86400
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt;: Allows requests from frontendcamp.in&lt;br&gt;
&lt;code&gt;Access-Control-Allow-Methods&lt;/code&gt;: Specifies allowed HTTP methods&lt;br&gt;
&lt;code&gt;Access-Control-Allow-Headers&lt;/code&gt;: Lists allowed custom headers&lt;br&gt;
&lt;code&gt;Access-Control-Max-Age&lt;/code&gt;: Tells the browser how long to cache the preflight response (in seconds)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The actual request is made.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Preflight requests can introduce performance overhead. To mitigate this, it's important to set the &lt;code&gt;Access-Control-Max-Age&lt;/code&gt; header to leverage browser caching.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;h2&gt;
  
  
  Common CORS Issues
&lt;/h2&gt;

&lt;p&gt;The knowledge you've gained so far should be enough to debug most CORS-related issues.&lt;/p&gt;

&lt;p&gt;Now, let's go through some common scenarios.&lt;/p&gt;


&lt;div class="crayons-card c-embed"&gt;

  

&lt;p&gt;❗ No 'Access-Control-Allow-Origin' header in response&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Access to fetch at &lt;span class="s1"&gt;'https://api.dev.to/data'&lt;/span&gt; from origin &lt;span class="s1"&gt;'https://frontendcamp.in'&lt;/span&gt; has been blocked by CORS policy:
Response to preflight request doesn&lt;span class="s1"&gt;'t pass access control check: No '&lt;/span&gt;Access-Control-Allow-Origin&lt;span class="s1"&gt;' header is present on the requested resource.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Cause&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The API does not send the Access-Control-Allow-Origin header.&lt;/li&gt;
&lt;li&gt;The browser blocks the request because it doesn't see explicit permission.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Fix&lt;/em&gt;&lt;br&gt;
Modify the API response to include &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header.&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;




&lt;div class="crayons-card c-embed"&gt;

  &lt;br&gt;
❗ The Request requires Preflight, but the Server doesn’t handle &lt;code&gt;OPTIONS&lt;/code&gt;&lt;br&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Access to fetch at &lt;span class="s1"&gt;'https://api.dev.to/data'&lt;/span&gt; from origin &lt;span class="s1"&gt;'https://frontendcamp.in'&lt;/span&gt; has been blocked by CORS policy:
Response to preflight request doesn&lt;span class="s1"&gt;'t pass access control check: The server does not respond to OPTIONS requests.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Cause&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The API does not handle OPTIONS requests, which are sent as preflight before the actual request.&lt;/li&gt;
&lt;li&gt;This happens when using PUT, DELETE, or custom headers (Authorization, X-Requested-With).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Fix&lt;/em&gt;&lt;br&gt;
Enable handling for OPTIONS requests on the server.&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;




&lt;div class="crayons-card c-embed"&gt;

  &lt;br&gt;
❗ The API allows a specific Origin, but the Frontend uses a different one&lt;br&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Access to fetch at &lt;span class="s1"&gt;'https://api.dev.to/data'&lt;/span&gt; from origin &lt;span class="s1"&gt;'https://sub.frontendcamp.in'&lt;/span&gt; has been blocked by CORS policy:
The &lt;span class="s1"&gt;'Access-Control-Allow-Origin'&lt;/span&gt; header does not match the request origin.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Cause&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The backend only allows &lt;code&gt;https://frontendcamp.in&lt;/code&gt;, but the request comes from &lt;code&gt;https://sub.frontendcamp.in&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Many sites use subdomains, and they are treated as separate origins.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Fix&lt;/em&gt;&lt;br&gt;
Whitelist the subdomain too.&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;




&lt;div class="crayons-card c-embed"&gt;

  &lt;br&gt;
❗ Credentialed requests (&lt;code&gt;withCredentials: true&lt;/code&gt;) not working&lt;br&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Access to fetch at &lt;span class="s1"&gt;'https://api.dev.to/data'&lt;/span&gt; from origin &lt;span class="s1"&gt;'https://frontendcamp.in'&lt;/span&gt; has been blocked by CORS policy:
The value of the &lt;span class="s1"&gt;'Access-Control-Allow-Origin'&lt;/span&gt; header &lt;span class="k"&gt;in &lt;/span&gt;the response must not be &lt;span class="s1"&gt;'*'&lt;/span&gt;
when the request’s credentials mode is &lt;span class="s1"&gt;'include'&lt;/span&gt;&lt;span class="nb"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Cause&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The request includes credentials (cookies, authentication tokens, etc.), but the server is allowing &lt;code&gt;*&lt;/code&gt; as &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When using credentials, &lt;code&gt;*&lt;/code&gt; is not allowed — the API must explicitly list allowed origins.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Fix&lt;/em&gt;&lt;br&gt;
Allow credentials &amp;amp; set a specific origin.&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;






&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts frontend code from making cross-origin requests. It’s not an error but a safeguard.&lt;/li&gt;
&lt;li&gt;Browsers enforce the Same-Origin Policy (SOP) to prevent malicious websites from accessing resources on other domains.&lt;/li&gt;
&lt;li&gt;The server must explicitly allow cross-origin requests by setting the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; header with the frontend’s origin.&lt;/li&gt;
&lt;li&gt;Using * allows any website to access the resource, which can be a security risk. It should only be used when absolutely necessary.&lt;/li&gt;
&lt;li&gt;If you're requesting data from a third-party API and can’t modify its response headers, a proxy server can bypass CORS restrictions.&lt;/li&gt;
&lt;li&gt;When a request is not simple, the browser sends an &lt;code&gt;OPTIONS&lt;/code&gt; request before the actual request to check if the server allows it.&lt;/li&gt;
&lt;li&gt;Requests that use methods other than &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, or &lt;code&gt;HEAD&lt;/code&gt;, include custom headers (e.g., &lt;code&gt;Authorization&lt;/code&gt;), or send non-standard content types are said to be not "simple".&lt;/li&gt;
&lt;li&gt;Frequent preflight requests can cause overhead. Setting the Access-Control-Max-Age header allows the browser to cache the response and improve performance.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Thank you for reading my post. 🙏 I hope you liked it.&lt;/p&gt;


&lt;div class="crayons-card c-embed"&gt;

  
&lt;h3&gt;
  
  
  Preparing for Frontend interviews?
&lt;/h3&gt;

&lt;p&gt;👉 Check out &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Popular interview questions&lt;/li&gt;
&lt;li&gt;Popular frontend system design questions &lt;em&gt;(upcoming)&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;All for free! ✨&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://frontendcamp.in" class="ltag_cta ltag_cta--branded" rel="noopener noreferrer"&gt;Join now! 🚀&lt;/a&gt;
&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;


</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>interview</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Event Delegation Pattern</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Tue, 21 Jan 2025 15:24:22 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/event-delegation-pattern-42m9</link>
      <guid>https://forem.com/thesanjeevsharma/event-delegation-pattern-42m9</guid>
      <description>&lt;p&gt;Event delegation is a design pattern in JavaScript used to efficiently handle events on multiple child elements by adding a single event handler to a common ancestor element. When used correctly, this pattern can significantly improve performance.&lt;/p&gt;

&lt;p&gt;Consider the following HTML structure:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2eufxbbd3sbj6n2vrntq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2eufxbbd3sbj6n2vrntq.png" alt="Event delegation" width="800" height="443"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The parent element is a &lt;code&gt;div&lt;/code&gt; with the &lt;code&gt;id&lt;/code&gt; of &lt;code&gt;container&lt;/code&gt;, and it contains multiple &lt;code&gt;button&lt;/code&gt; elements as its children. Traditionally, if we wanted to trigger a function when any button is clicked, we would attach a separate click event handler to each button.&lt;/p&gt;

&lt;p&gt;Event delegation takes a different approach. Instead of attaching multiple event handlers, we attach a single event handler to the parent element (i.e., the &lt;code&gt;container&lt;/code&gt;). Within the parent element's event handler function, we can identify the specific child element that triggered the event.&lt;/p&gt;

&lt;p&gt;But how does this work?&lt;/p&gt;

&lt;p&gt;It’s possible because of event bubbling. Most events in the DOM bubble up from the target element (where the event occurred) to the root DOM node. This allows the parent element to listen for events triggered by its child elements.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you'd like to dive deeper into event bubbling and capturing, check out this &lt;a href="https://www.frontendcamp.in/open-questions/event-bubbling-capturing" rel="noopener noreferrer"&gt;detailed explanation&lt;/a&gt;.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="cm"&gt;/*
 * &amp;lt;div id="container"&amp;gt;
 *   &amp;lt;button&amp;gt;Item 1&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 2&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 3&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 4&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 5&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 6&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 7&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 8&amp;lt;/button&amp;gt;
 *   &amp;lt;button&amp;gt;Item 9&amp;lt;/button&amp;gt;
 * &amp;lt;/div&amp;gt;
 */&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;container&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;#container&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;container&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// gives the element that triggered the event&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;textContent&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Item 5&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;When &lt;code&gt;Item 5&lt;/code&gt; is clicked, the event from the button bubbles up, and we intercept it in the &lt;code&gt;container&lt;/code&gt;'s event handler. The &lt;code&gt;event.target&lt;/code&gt; property provides a reference to the specific element that triggered the event.&lt;/p&gt;
&lt;h2&gt;
  
  
  Benefits of Event Delegation
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Efficiency&lt;/strong&gt;: No matter how many child elements we have — even thousands — we only use a single event handler. This approach conserves memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic Elements&lt;/strong&gt;: When elements are added or removed dynamically, we don't need to manually add or remove event listeners for those elements.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Common Pitfalls
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Be mindful of event types&lt;/strong&gt;: Events such as blur, focus, and mouseenter do not bubble up, so event delegation cannot be used for handling them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ensure the correct target element&lt;/strong&gt;: Always validate the target element to avoid triggering unintended actions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complex logic&lt;/strong&gt;: While this approach is efficient, managing all events in a single handler can become complex if the logic isn’t well-structured.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;React delegates all events to the root node by default. Even if you add multiple &lt;code&gt;onClick&lt;/code&gt; handlers to child elements, React does not attach event listeners directly to those child DOM elements. Instead, it uses a Synthetic Event System, which normalizes event behavior across browsers and efficiently manages events through event delegation.&lt;/p&gt;
&lt;/blockquote&gt;


&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Event delegation is a JavaScript design pattern that optimizes event handling by attaching a single event listener to a common ancestor element instead of adding listeners to multiple child elements.&lt;/li&gt;
&lt;li&gt;It relies on event bubbling, where events propagate from the target element to parent elements up to the root DOM node.&lt;/li&gt;
&lt;li&gt;It reduces memory usage by using a single event handler regardless of the number of child elements and automatically handles dynamically added or removed child elements without requiring additional event listeners.&lt;/li&gt;
&lt;li&gt;Certain events, such as &lt;code&gt;blur&lt;/code&gt;, &lt;code&gt;focus&lt;/code&gt;, and &lt;code&gt;mouseenter&lt;/code&gt;, do not bubble up and cannot be delegated.&lt;/li&gt;
&lt;li&gt;React uses event delegation by default, attaching all event listeners to the root node via its Synthetic Event System.&lt;/li&gt;
&lt;/ol&gt;




&lt;div class="crayons-card c-embed"&gt;

  
&lt;h3&gt;
  
  
  Preparing for Frontend interviews?
&lt;/h3&gt;

&lt;p&gt;👉 Check out &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Popular interview questions&lt;/li&gt;
&lt;li&gt;Popular frontend system design questions &lt;em&gt;(upcoming)&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;All for free! ✨&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://frontendcamp.in" class="ltag_cta ltag_cta--branded" rel="noopener noreferrer"&gt;Join now! 🚀&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;Watch my dev vlogs here: &lt;a href="https://www.youtube.com/watch?v=C2Sm-dtN9Ro" rel="noopener noreferrer"&gt;YouTube 🎥&lt;/a&gt;&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>frontend</category>
      <category>interview</category>
    </item>
    <item>
      <title>10 Backend Terms Every Frontend Developer Should Know</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Thu, 09 Jan 2025 21:09:19 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/10-backend-terms-every-frontend-developer-should-know-2o2h</link>
      <guid>https://forem.com/thesanjeevsharma/10-backend-terms-every-frontend-developer-should-know-2o2h</guid>
      <description>&lt;p&gt;When a backend dev gives their update in the daily standup meeting, most frontend devs are clueless about the work they're doing. They use a lot of jargons that sound gibberish to us frontend devs. But not anymore! 😎&lt;/p&gt;

&lt;p&gt;This post aims to tackle some of those jargons. Why should you learn these, you ask? First, you’ll start to understand your product's architecture a bit more. Second, don’t limit yourself to frontend — being an engineer means having a well-rounded understanding of other domains too.&lt;/p&gt;

&lt;p&gt;Remember, backend devs aren’t trying to confuse anyone — they’re just speaking the language of their domain. Let’s break it down into simpler terms and demystify concepts like rate limiting, load balancing, proxies, and many more.&lt;/p&gt;

&lt;p&gt;Ready? Let’s dive in! 💪&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Rate Limiting
&lt;/h2&gt;

&lt;p&gt;Rate limiting is a way to control the number of requests a client (like a user, app, or system) can make to a server within a specific period. Think of it as a traffic cop ensuring no one overuses or abuses the server's resources.&lt;/p&gt;

&lt;p&gt;For example, a server may allow 100 requests per minute from a single client. If the client exceeds this limit, the server will reject additional requests, often with a 429 (Too Many Requests) response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy2gxsqrmev826mrb4leu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy2gxsqrmev826mrb4leu.png" alt="Rate limiting" width="800" height="422"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Rate Limiting:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prevent Abuse and Overload: Rate limiting ensures no single user or system overwhelms the server by sending excessive requests, which could crash the server.&lt;/li&gt;
&lt;li&gt;Control Costs: Helps avoid unexpectedly high resource usage (like bandwidth or compute power), which can be costly. For instance, limiting API calls to a free-tier user's account to avoid excessive use without payment.&lt;/li&gt;
&lt;li&gt;Enhance Security: Helps mitigate attacks like DDoS (Distributed Denial-of-Service) by blocking excessive requests from attackers.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  2. Load Balancing
&lt;/h2&gt;

&lt;p&gt;Load balancing is a way to distribute incoming requests or traffic across multiple servers to ensure no single server gets overwhelmed. Think of it as a traffic cop directing cars (requests) to different lanes (servers) to keep everything running smoothly.&lt;/p&gt;

&lt;p&gt;For example, Social media platforms like Instagram have millions of users accessing its servers simultaneously. Instead of sending all those users to one server, a load balancer ensures their requests are spread across several servers.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fic3put9khqzo8wr5yu46.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fic3put9khqzo8wr5yu46.png" alt="Load balancer" width="800" height="473"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Load Balancing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Avoid Overloading Servers: If all traffic goes to one server, it might crash due to excessive load. Load balancing prevents this by distributing requests evenly.&lt;/li&gt;
&lt;li&gt;Improve Performance and Speed: By spreading traffic, each server handles a manageable number of requests, leading to faster responses for users.&lt;/li&gt;
&lt;li&gt;Scale Applications: As traffic increases, you can add more servers to the pool, and the load balancer will automatically start distributing traffic to the new servers.&lt;/li&gt;
&lt;li&gt;Ensure High Availability: If one server fails, the load balancer redirects traffic to the other working servers, ensuring the website or service stays online.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  3. Caching
&lt;/h2&gt;

&lt;p&gt;Caching is a way to store frequently accessed data temporarily so that it can be retrieved quickly without repeatedly fetching it from the original source.&lt;/p&gt;

&lt;p&gt;Think of it like keeping a frequently used recipe on your kitchen counter. Instead of searching for it in a cookbook every time you need it, you grab it from the counter, saving time and effort.&lt;/p&gt;

&lt;p&gt;Most backend systems use Caching for storing frequently used database query results, API responses, or pre-rendered web pages. &lt;a href="https://redis.io/" rel="noopener noreferrer"&gt;Redis&lt;/a&gt; is popular choice among backend developers for caching data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkeq7b03jfjnykxyg7j9n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkeq7b03jfjnykxyg7j9n.png" alt="Caching" width="800" height="473"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Caching:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Speed Up Performance: Fetching data from a cache is much faster than getting it from the original source (e.g., a database or server).&lt;/li&gt;
&lt;li&gt;Reduce Load on Servers: By serving data from the cache, you reduce the number of requests to the backend, preventing it from being overwhelmed.&lt;/li&gt;
&lt;li&gt;Handle High Traffic: During peak usage, caching helps ensure the system can handle many users without slowing down.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  4. CDN
&lt;/h2&gt;

&lt;p&gt;A CDN (Content Delivery Network) is a network of servers distributed across different locations that work together to deliver content to users more quickly. It helps speed up the process of loading websites, images, videos, and other content by serving them from a server that is geographically closer to the user.&lt;/p&gt;

&lt;p&gt;Imagine a library with books stored in different branches. Instead of always going to the central library to get a book, you can visit the closest branch and get the book faster. A CDN does something similar by storing copies of website content in multiple locations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx10539xrt4uw50c21nxj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx10539xrt4uw50c21nxj.png" alt="CDN explained" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of CDN:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Faster Load Times: By serving content from a server closer to the user, a CDN reduces the distance data has to travel, leading to faster load times.&lt;/li&gt;
&lt;li&gt;Better Scalability and Reliability: CDNs make it easier for websites to scale by automatically handling a large number of users. If one server goes down, CDNs can route the traffic to another server without affecting the user experience.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  5. Microservices
&lt;/h2&gt;

&lt;p&gt;Microservices is an architectural style where an application is divided into smaller, independent services, each responsible for a specific piece of functionality. Each microservice is like a small building block that focuses on one task and communicates with other services to create the full application.&lt;/p&gt;

&lt;p&gt;Imagine a company where each department (sales, marketing, finance, etc.) works independently but collaborates to run the business. Similarly, in a microservices architecture, each service (like user management, payment processing, etc.) works on its own but interacts with others to make the whole system work.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxbai8e81xs0n7crm2zpq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxbai8e81xs0n7crm2zpq.png" alt="Microservices architecture" width="800" height="295"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The opposite of Microservices is Monolithic architecture, where all the functionality of an application is combined into a single, unified service or codebase.&lt;/p&gt;

&lt;p&gt;Usage of Microservices:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scalability: Since each service is independent, you can scale them individually. For example, if the payment processing service gets more traffic, you can scale just that service without affecting the others.&lt;/li&gt;
&lt;li&gt;Flexibility and Technology Choices: Each microservice can be built with a different technology stack, allowing teams to choose the best tool for each job. For example, You could use Python for data analytics and Node.js for real-time chat without worrying about compatibility.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  6. API Gateway
&lt;/h2&gt;

&lt;p&gt;An API Gateway is a server that acts as an entry point for all client requests to your system. It routes those requests to the appropriate microservice, handles load balancing, authentication, caching, and other tasks. In simple terms, it’s like a doorman who directs visitors to the right department in a large building.&lt;/p&gt;

&lt;p&gt;Imagine a large organization with many departments (microservices), and instead of going directly to each department, visitors (users) go through a central reception (API Gateway) that sends them to the right place.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://konghq.com/products/kong-gateway" rel="noopener noreferrer"&gt;Kong&lt;/a&gt; is a popular open-source API gateway used by backend developers.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9hwl0c0b2wiplmh6cy1g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9hwl0c0b2wiplmh6cy1g.png" alt="API Gateway" width="800" height="384"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of API Gateway:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Single Entry Point: It simplifies the interaction between clients and the backend services by providing a single entry point for all requests, rather than having clients talk to multiple microservices directly. The API Gateway directs requests to the correct microservice based on the URL, method, or other factors, acting as a traffic controller.&lt;/li&gt;
&lt;li&gt;Logging and Monitoring: It collects logs and metrics for all requests passing through, helping to monitor the system and debug issues.&lt;/li&gt;
&lt;li&gt;Security: It rate limits, load balances and check for authentication token in incoming requests.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  7. Webhook
&lt;/h2&gt;

&lt;p&gt;A Webhook is a way for one application to send real-time updates or notifications to another application when a specific event happens. Instead of the receiving application repeatedly checking for updates (polling), the sending application automatically sends the information when needed.&lt;/p&gt;

&lt;p&gt;For example, when something important happens (like a package delivery), the sender (delivery service) texts you (the recipient) immediately, instead of you having to constantly check the website for updates.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fze9qqojbeqtsbi63pzu7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fze9qqojbeqtsbi63pzu7.png" alt="Webhook explained" width="800" height="349"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Webhooks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Real-Time Notifications: Webhooks provide instant updates, eliminating delays caused by periodic polling.&lt;/li&gt;
&lt;li&gt;Automation: Webhooks enable automatic workflows between different applications or systems.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  8. Sharding
&lt;/h2&gt;

&lt;p&gt;Sharding is a method of splitting a large database into smaller, more manageable pieces, called shards. Each shard holds a portion of the data and operates as an independent database.&lt;/p&gt;

&lt;p&gt;Think of sharding as dividing a library's books into multiple sections based on genres. Instead of searching the entire library for a book, you only look in the relevant section, making the process faster and more efficient.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5d97i4sadbwaarsv6gfv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5d97i4sadbwaarsv6gfv.png" alt="Database Sharding" width="800" height="405"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Sharding:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Improved Performance: By dividing data across multiple shards, the workload is distributed. This reduces the load on any single database and allows queries to be processed faster.&lt;/li&gt;
&lt;li&gt;High Availability: If one shard goes down, only a portion of the data is affected. The rest of the system continues to work, making it more resilient.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  9. Proxy
&lt;/h2&gt;

&lt;p&gt;A Proxy is a server that acts as an intermediary between a client (like your browser) and another server (like a website). Instead of connecting directly to the server, your request goes through the proxy, which forwards it to the destination and then sends the response back to you.&lt;/p&gt;

&lt;p&gt;Think of it like a middleman: if you want to send a message to someone, you give it to the middleman, who delivers it for you and brings back the reply.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnr9gnbvfxv5l9phg0hxx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnr9gnbvfxv5l9phg0hxx.png" alt="Proxy server" width="800" height="258"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Proxy servers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Privacy and Anonymity: A proxy hides your identity by masking your IP address. The destination server only sees the proxy's IP, not yours.&lt;/li&gt;
&lt;li&gt;Bypassing Restrictions: Proxies allow users to access content that might be blocked in their region by routing requests through a server in a different location.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  10. Message Queues
&lt;/h2&gt;

&lt;p&gt;A Message Queue is a system used to send, store, and retrieve messages between different parts of an application (or between applications) in a reliable and organized way. Instead of sending messages directly, a queue acts like a post office:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One part of the system (the sender) places a message in the queue.&lt;/li&gt;
&lt;li&gt;Another part (the receiver) picks it up whenever it’s ready to process it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://www.rabbitmq.com/" rel="noopener noreferrer"&gt;RabbitMQ&lt;/a&gt; and &lt;a href="https://kafka.apache.org/" rel="noopener noreferrer"&gt;Apache Kafka&lt;/a&gt; are two popular message queue systems,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqit1lj9ersi22bb8c1i2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqit1lj9ersi22bb8c1i2.png" alt="Message Queue" width="800" height="560"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage of Message Queues:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Decoupling Systems: A message queue allows different parts of a system to work independently. The sender and receiver don’t need to know about each other or work at the same time.&lt;/li&gt;
&lt;li&gt;Asynchronous Processing: Message queues enable background tasks to be handled without making the user wait. For example, When you upload a photo, the app instantly confirms the upload while processing resizing and optimization tasks in the background.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Thank you for reading my post! 🙏 I hope you've learnt something today.&lt;/p&gt;

&lt;p&gt;Please leave a reaction 🦄 or a comment 💬, so this post reaches other devs like you. 🌱👨‍💻&lt;/p&gt;


&lt;div class="crayons-card c-embed"&gt;

  
&lt;h3&gt;
  
  
  Preparing for Frontend interviews?
&lt;/h3&gt;

&lt;p&gt;👉 Check out &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Popular interview questions&lt;/li&gt;
&lt;li&gt;Popular frontend system design questions &lt;em&gt;(upcoming)&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;All for free! ✨&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://frontendcamp.in" class="ltag_cta ltag_cta--branded" rel="noopener noreferrer"&gt;Join now! 🚀&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;OR&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/thesanjeevsharma/series/28387" class="ltag_cta ltag_cta--branded"&gt;Check out the interview series on DEV!&lt;/a&gt;
&lt;br&gt;

&lt;/p&gt;
&lt;/div&gt;


</description>
      <category>frontend</category>
      <category>webdev</category>
      <category>backend</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Event Flow: Bubbling &amp; Capturing</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Wed, 08 Jan 2025 16:33:31 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/event-flow-bubbling-capturing-37h0</link>
      <guid>https://forem.com/thesanjeevsharma/event-flow-bubbling-capturing-37h0</guid>
      <description>&lt;p&gt;This is post #7 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider joining &lt;a href="https://www.frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt; 💚.&lt;/p&gt;




&lt;p&gt;Event bubbling and capturing, both are propagation mechanisms in DOM(Document Object Model). Both these mechanisms are opposite of each other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Event Bubbling
&lt;/h2&gt;

&lt;p&gt;In Event bubbling, the event, after triggering the handler on the target element(&lt;code&gt;event.target&lt;/code&gt;) propagates upwards(bubbles) to the root element of the document. On its way it triggers all the event handlers on the parent elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="cm"&gt;/*
&amp;lt;div id="container"&amp;gt;
  Hello world!
  &amp;lt;button id="btn"&amp;gt;Click me&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
*/&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;container&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getElementById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;container&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;container&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Container handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;btn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getElementById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;btn&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;btn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Button handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the snippet above, when you click the button you'll see the following output in console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="s2"&gt;"Button handler"&lt;/span&gt;
&lt;span class="s2"&gt;"Container handler"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First the handler on the button is called and the &lt;code&gt;event.target&lt;/code&gt; property is set to &lt;code&gt;button&lt;/code&gt; as it initiated the event. Event on its way up to the root element, it calls its parent's event handler.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Almost all events bubble but there are a few exceptions like &lt;code&gt;focus&lt;/code&gt; event that do not bubble.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can stop bubbling by calling the &lt;code&gt;stopPropagation()&lt;/code&gt; method on the event. If the button's event handler in the above snippet stops propagation, the container's event handler won't be called.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;btn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Button handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="c1"&gt;// ancestor elements won't receive the event&lt;/span&gt;
  &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stopPropagation&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can access the element that initiated the event by accessing &lt;code&gt;target.event&lt;/code&gt; property. Also, the element whose handler is being executed can be accessed using &lt;code&gt;event.currentTarget&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;container&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Container handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 'Container handler!'&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// btn&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;currentTarget&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// container&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// container&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Want to learn more about the &lt;code&gt;this&lt;/code&gt; keyword? &lt;a href="https://dev.to/thesanjeevsharma/this-in-javascript-explained-1pgg"&gt;I wrote a post on it&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Event Capturing
&lt;/h2&gt;

&lt;p&gt;We've only been seeing half the picture until now. When the button in the above snippet is clicked, it isn't the first element to receive that event. 👀&lt;/p&gt;

&lt;p&gt;The event flow consists of three phases:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Capturing phase: The event flows from the root element to the target element.&lt;/li&gt;
&lt;li&gt;Target phase: The event is received on the target element.&lt;/li&gt;
&lt;li&gt;Bubbling phase: The event starts propagating back to the root element.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjf7tcuuna30g6se0argi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjf7tcuuna30g6se0argi.png" alt="Event Capturing and Bubbling" width="800" height="514"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By default, all event handlers are only called during target and bubbling phase. To call event handlers in the capturing phase, pass &lt;code&gt;true&lt;/code&gt; as the third argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;el&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{},&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="c1"&gt;// or to be more explicit&lt;/span&gt;
&lt;span class="nx"&gt;el&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{},&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;capture&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;If you are using a handler in &lt;code&gt;capturing&lt;/code&gt; phase, it won't be called in the &lt;code&gt;bubbling&lt;/code&gt; phase.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similar to bubbling, when &lt;code&gt;event.stopPropagation()&lt;/code&gt; is called during the capturing phase it won't let the event flow further i.e. down the DOM, in this case.&lt;/p&gt;

&lt;p&gt;In the snippet we discussed earlier, if &lt;code&gt;container&lt;/code&gt; stops propagation during capturing phase, the button's handler will never be called.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="cm"&gt;/*
&amp;lt;div id="container"&amp;gt;
  Hello world!
  &amp;lt;button id="btn"&amp;gt;Click me&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
*/&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;container&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getElementById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;container&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;container&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Container handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stopPropagation&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// capturing phase&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;btn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getElementById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;btn&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;btn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// this will never be logged&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Button handler!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is why you should always have a good reason to use &lt;code&gt;event.stopPropagation()&lt;/code&gt;. It can lead to unexpected issues that are hard to debug in a complex or deeply nested DOM tree.&lt;/p&gt;

&lt;p&gt;Event capturing is rarely used compared to Bubbling. Bubbling has a lot of use cases like "Event delegation" - an important performance pattern.&lt;/p&gt;

&lt;p&gt;This post lays down the foundation for the next topic - Event delegation. Make sure you understand it well. Have doubts? Leave them in the comments. ✌️&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Event flow consists of three phases: &lt;code&gt;Capturing&lt;/code&gt;, &lt;code&gt;Target&lt;/code&gt; and &lt;code&gt;Bubbling&lt;/code&gt; phase.&lt;/li&gt;
&lt;li&gt;In the capturing phase, event flows down from the root element to the target(&lt;code&gt;event.target&lt;/code&gt;) element.&lt;/li&gt;
&lt;li&gt;In the bubbling phase, event flows from the target element to the root element.&lt;/li&gt;
&lt;li&gt;By default, all event handlers are called only during target and bubbling phase.&lt;/li&gt;
&lt;li&gt;By passing a third argument in the &lt;code&gt;addEventListener&lt;/code&gt; function, you can set the handler on the capturing phase.&lt;/li&gt;
&lt;li&gt;At any point in the event flow, calling &lt;code&gt;event.stopPropagation()&lt;/code&gt; will stop the event from flowing further.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Like what you just read? 👉 Consider joining the waitlist on &lt;a href="https://www.frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Leave some reactions "🦄" and comments so this post helps other devs like you. 🙏&lt;/p&gt;

</description>
      <category>frontend</category>
      <category>javascript</category>
      <category>interview</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Cookies, Local storage and Session storage</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Sun, 05 Jan 2025 06:06:29 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/cookies-local-storage-and-session-storage-1hkm</link>
      <guid>https://forem.com/thesanjeevsharma/cookies-local-storage-and-session-storage-1hkm</guid>
      <description>&lt;p&gt;This is post #6 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on &lt;a href="https://www.frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;Cookies, Local Storage, and Session Storage are all used to store data on the client side. These mechanisms are particularly useful for storing authentication tokens or client-only states, such as themes or personalized settings. All three storage types share the following characteristics:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;They store data as key-value pairs.&lt;/li&gt;
&lt;li&gt;All values are stored in string format. If a value is not a string, it is serialized before being stored.&lt;/li&gt;
&lt;li&gt;Data stored in these mechanisms is accessible to the client (except for HttpOnly cookies).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Cookies
&lt;/h2&gt;

&lt;p&gt;Cookies cannot store large amounts of data; their storage is capped at approximately 4KB per domain. This limitation exists because cookies are automatically sent to the server with every request made by the browser. Storing excessive client-side data in cookies would increase the payload size, negatively impacting performance.&lt;/p&gt;

&lt;p&gt;What kind of data should we store in Cookies?&lt;br&gt;
Cookies are ideal for storing data that needs to be transmitted to the server, such as authentication tokens, session IDs, analytics IDs, and similar information. Additionally, cookies allow data sharing across different tabs or windows of the same domain or subdomain.&lt;/p&gt;

&lt;p&gt;You can configure cookies using various flags to tweak their behavior or enforce security:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;HttpOnly&lt;/code&gt; ensures cookies are inaccessible via JavaScript on the client side, mitigating the risk of XSS attacks.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;maxAge&lt;/code&gt;/&lt;code&gt;expires&lt;/code&gt; specifies an expiry date for the cookie. If no expiry date is set, the cookie is deleted when the browser is closed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Want to learn more about cookie flags? Check out my &lt;a href="https://www.linkedin.com/posts/thesanjeevsharma_websecurity-frontend-webdevelopment-activity-7274750938408456192-0jAW" rel="noopener noreferrer"&gt;LinkedIn post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unlike local storage and session storage, cookies can also be set (read: "added") by the server using the &lt;code&gt;Set-Cookie&lt;/code&gt; header.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Set a cookie for the key `token` that `expires` on 1st March 2025.&lt;/span&gt;
&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cookie&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
  &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;token=a1-b2-c3; expires=Sat, 1 Mar 2025 23:59:59 GMT; path=/&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Read all cookies. There's no way to read specific cookies using `document.cookie`.&lt;/span&gt;
&lt;span class="c1"&gt;// You have to parse the string yourself.&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cookie&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// token=a1-b2-c3&lt;/span&gt;

&lt;span class="c1"&gt;// Delete the cookie with the key `token` by setting an&lt;/span&gt;
&lt;span class="c1"&gt;// expiry date in the past. The value doesn't matter.&lt;/span&gt;
&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cookie&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;token=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Local storage
&lt;/h2&gt;

&lt;p&gt;Unlike cookies, &lt;code&gt;localStorage&lt;/code&gt; offers a significantly larger storage capacity of approximately 5MB per domain. This is because &lt;code&gt;localStorage&lt;/code&gt; is designed for storing long-term data. It retains data even when the browser is closed, making it ideal for persistent client-side storage needs.&lt;/p&gt;

&lt;p&gt;What kind of data should we store in &lt;code&gt;localStorage&lt;/code&gt; then?&lt;br&gt;
&lt;code&gt;localStorage&lt;/code&gt; is best suited for storing data that is used only on the client side and does not need to be sent to the server with every request. Some examples are the theme of a website or products added in cart before a used has signed in.&lt;/p&gt;

&lt;p&gt;Data stored in &lt;code&gt;localStorage&lt;/code&gt; persists indefinitely until the user deletes it manually or the website clears it using JavaScript.&lt;/p&gt;

&lt;p&gt;Similar to cookies, data in &lt;code&gt;localStorage&lt;/code&gt; is accessible across all tabs or windows of the same origin, making it useful for sharing client-side state within a domain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Set a value in localStorage.&lt;/span&gt;
&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;theme&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;dark&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Get a value from localStorage.&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;theme&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// 'dark'&lt;/span&gt;

&lt;span class="c1"&gt;// Remove a value from localStorage.&lt;/span&gt;
&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;removeItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;theme&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Clear all data in localStorage.&lt;/span&gt;
&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Session storage
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;sessionStorage&lt;/code&gt; is used to store short-lived, client side data. Like &lt;code&gt;localStorage&lt;/code&gt;, it provides a storage capacity of around 5MB per domain and shares the same API.&lt;/p&gt;

&lt;p&gt;While both &lt;code&gt;sessionStorage&lt;/code&gt; and &lt;code&gt;localStorage&lt;/code&gt; share similar functionalities, they differ in two key aspects: &lt;em&gt;Data persistence&lt;/em&gt; and &lt;em&gt;Accessibility&lt;/em&gt;.&lt;br&gt;
Unlike &lt;code&gt;localStorage&lt;/code&gt;, &lt;code&gt;sessionStorage&lt;/code&gt; does not retain data once the tab or browser is closed. Additionally, data stored in &lt;code&gt;sessionStorage&lt;/code&gt; is isolated to the specific tab or window where it was created, meaning other tabs or windows from the same origin cannot access it.&lt;/p&gt;

&lt;p&gt;What's the use case for &lt;code&gt;sessionStorage&lt;/code&gt; then?&lt;br&gt;
&lt;code&gt;sessionStorage&lt;/code&gt; is ideal for storing data that is needed only for a single session. For instance, consider a user filling out a long form who accidentally refreshes the page. If the form data is stored in &lt;code&gt;sessionStorage&lt;/code&gt;, it will persist through the refresh, allowing the user to continue without losing their progress.&lt;/p&gt;

&lt;p&gt;However, it's important to note that this data will not be accessible in a different tab or once the tab is closed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Set a value in sessionStorage.&lt;/span&gt;
&lt;span class="nx"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;username&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;johndoe&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Get a value from sessionStorage.&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;username&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// 'johndoe'&lt;/span&gt;

&lt;span class="c1"&gt;// Remove a value from sessionStorage.&lt;/span&gt;
&lt;span class="nx"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;removeItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;username&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Clear all data in sessionStorage.&lt;/span&gt;
&lt;span class="nx"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;While cookies are automatically included in every request sent by the browser, data stored in &lt;code&gt;localStorage&lt;/code&gt; or &lt;code&gt;sessionStorage&lt;/code&gt; can be manually transmitted to the server by writing custom code.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Cookies, &lt;code&gt;localStorage&lt;/code&gt; and &lt;code&gt;sessionStorage&lt;/code&gt; are used to store data on client side.&lt;/li&gt;
&lt;li&gt;Cookies are the only form of storage which can be set by the server too using &lt;code&gt;Set-Cookie&lt;/code&gt; response header.&lt;/li&gt;
&lt;li&gt;Cookies are automatically sent to the server with every request.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;localStorage&lt;/code&gt; and &lt;code&gt;sessionStorage&lt;/code&gt; have a significantly large storage(5MB) compared to the cookies(4KB). Both of these storages share the same API interface.&lt;/li&gt;
&lt;li&gt;Cookies have an expiry date, if not, they are cleared when the browser is closed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;localStorage&lt;/code&gt; data persists indefinitely unless manually cleared by the user or the website itself.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sessionStorage&lt;/code&gt; data is cleared after the session ends i.e. when the tab or the window is closed.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Like what you just read? Consider checking out &lt;a href="https://www.frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt; ✌️&lt;/p&gt;

</description>
      <category>frontend</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>interview</category>
    </item>
    <item>
      <title>`this` in JavaScript Explained</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Tue, 24 Dec 2024 17:26:51 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/this-in-javascript-explained-1pgg</link>
      <guid>https://forem.com/thesanjeevsharma/this-in-javascript-explained-1pgg</guid>
      <description>&lt;p&gt;This is question #5 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;The &lt;code&gt;this&lt;/code&gt; keyword always refers to the current context of a function or script.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;this&lt;/code&gt; is a confusing topic for most of us (pun intended), but it doesn't have to be. All you need to do is remember some rules.&lt;/p&gt;

&lt;p&gt;Following rules, in order of precedence, dictate how value of &lt;code&gt;this&lt;/code&gt; is determined during runtime:&lt;/p&gt;

&lt;h2&gt;
  
  
  Usage in a Function constructor
&lt;/h2&gt;

&lt;p&gt;If a function is called with the &lt;code&gt;new&lt;/code&gt; keyword, &lt;code&gt;this&lt;/code&gt; inside the function refers to the newly created object instance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;book1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Jungle Book&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// {}&lt;/span&gt;
&lt;span class="c1"&gt;// { title: "'Jungle Book' }"&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;book1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 'Jungle Book'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Explicitly binding &lt;code&gt;this&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;call()&lt;/code&gt;, &lt;code&gt;apply()&lt;/code&gt; or &lt;code&gt;bind()&lt;/code&gt; can be used to explicitly set the value of &lt;code&gt;this&lt;/code&gt; inside a function.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;call()&lt;/code&gt; and &lt;code&gt;apply()&lt;/code&gt; are used when a function needs to be invoked immediately.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;bind()&lt;/code&gt; returns a new function to be used later.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Ben&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Hello, &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;!`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sayHelloToBen&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;bind&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nf"&gt;sayHelloToBen&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Hello, Ben!&lt;/span&gt;
&lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Hello, Ben!&lt;/span&gt;
&lt;span class="nx"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Hello, Ben!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Usage in a method call
&lt;/h2&gt;

&lt;p&gt;If a function is a method of an object, then &lt;code&gt;this&lt;/code&gt; refers to the object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Ben&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;logThis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;logThis&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// { name: 'Ben', logThis: fn() }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Usage in a Regular function call (Free function invocation)
&lt;/h2&gt;

&lt;p&gt;If a function is invoked in the global context, then &lt;code&gt;this&lt;/code&gt; refers to the global object(in non-strict mode) or &lt;code&gt;undefined&lt;/code&gt;(in strict mode).&lt;/p&gt;

&lt;p&gt;For browsers, the global object is &lt;code&gt;window&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Browser&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Window { open: fn, alert: fn, ... }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a function is declared in the global context, it becomes a property of the &lt;code&gt;window&lt;/code&gt; object. Calling &lt;code&gt;window.showThis()&lt;/code&gt; would yield the same result. This is why it's an implicit method invocation. (Refer the rule above this one)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If multiple rules apply, then the rule with higher precedence will apply.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;obj1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;obj2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nx"&gt;obj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;obj2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// { value: 2 }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, two rules are being applied: Method invocation and Explicit binding. As explicit binding has higher precedence, it gets to set the value of &lt;code&gt;this&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Arrow functions
&lt;/h2&gt;

&lt;p&gt;Arrow functions don't follow the rules stated above as they don't have a &lt;code&gt;this&lt;/code&gt; value of their own. They pick the &lt;code&gt;this&lt;/code&gt; value from the &lt;strong&gt;parent scope&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Ben&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="na"&gt;showThisWrapped&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;arrowFn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nf"&gt;arrowFn&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;showThis&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Window { open: fn, alert: fn, ... }&lt;/span&gt;
&lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;showThisWrapped&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// { name: 'Ben', showThis: fn, showThisWrapped: fn }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is why you should avoid using arrow functions for event listeners. Event listeners bind the HTML element to the &lt;code&gt;this&lt;/code&gt; value but if the handler is an arrow function, it is not possible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;#cta&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// HTMLButtonElement&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;

&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;#cancel&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Window&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In a function constructor(&lt;code&gt;new Person()&lt;/code&gt;), &lt;code&gt;this&lt;/code&gt; will be the newly created object instance.&lt;/li&gt;
&lt;li&gt;If explicitly bound using &lt;code&gt;bind()&lt;/code&gt;, &lt;code&gt;call()&lt;/code&gt; or &lt;code&gt;apply()&lt;/code&gt;, &lt;code&gt;this&lt;/code&gt; inside the function will be set to the value provided.&lt;/li&gt;
&lt;li&gt;Inside a method, &lt;code&gt;this&lt;/code&gt; is set to the object that method is a property of.&lt;/li&gt;
&lt;li&gt;Inside a free function invocation, &lt;code&gt;this&lt;/code&gt; points to global object(non-strict mode) or &lt;code&gt;undefined&lt;/code&gt;(strict mode).&lt;/li&gt;
&lt;li&gt;If multiple rules apply, the rule stated first(1-4) will apply.&lt;/li&gt;
&lt;li&gt;Arrow functions don't have their own &lt;code&gt;this&lt;/code&gt;. Its value is picked from the parent scope.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Like what you just read? Consider joining the waitlist on &lt;a href="https://www.frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt; ✌️&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>interview</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Event Loop Explained</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Sat, 07 Sep 2024 13:14:25 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/event-loop-explained-59g7</link>
      <guid>https://forem.com/thesanjeevsharma/event-loop-explained-59g7</guid>
      <description>&lt;p&gt;Another one among the popular frontend interview questions. It tests interviewees depth of knowledge in JavaScript ecosystem.&lt;/p&gt;

&lt;p&gt;This is question #4 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;Before we dig into the event loop, I want you to look at the following illustration. You might not understand all the components mentioned here, but it's better to build a mental model before we start.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3g7q6lney9ckvkrtxojo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3g7q6lney9ckvkrtxojo.png" alt="Event Loop architecture" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We'll now zoom in on each of the components one by one and build our understanding of the Event Loop.&lt;/p&gt;

&lt;p&gt;You might be surprised to know that APIs like &lt;code&gt;fetch&lt;/code&gt; and &lt;code&gt;setTimeout&lt;/code&gt; are not native to JavaScript. These APIs are provided by the JavaScript runtime environment.&lt;/p&gt;

&lt;p&gt;Every JavaScript runtime comes with a JavaScript engine. In Chrome and Node.js, it's V8, and in Firefox, it's SpiderMonkey. The JavaScript engine mainly consists of two components: the Heap and the Call Stack.&lt;/p&gt;

&lt;p&gt;During execution, the Heap is used for dynamic memory allocation, and the Call Stack is used to store the execution context. We'll mainly focus on the Call Stack in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  Call Stack
&lt;/h2&gt;

&lt;p&gt;JavaScript, being a single-threaded language, comes with a single Call Stack. The Call Stack operates on the Last In, First Out (LIFO) principle. When a function execution starts, it is pushed onto the stack. After the execution is complete, it's popped off the stack, and the control returns to the calling function or the main program. This LIFO structure ensures that the most recently called function is always the first to complete.&lt;/p&gt;

&lt;p&gt;Here's an illustration to visualize it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fix5gcbzral844pqtk30a.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fix5gcbzral844pqtk30a.gif" alt="Working of Call Stack" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the script execution starts, the global execution context is created(let's call it &lt;code&gt;main()&lt;/code&gt;) and pushed onto the Call Stack, followed by:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;console.log("Hello")&lt;/code&gt; is pushed onto the call stack. Its output is logged in the console, and then it's finally popped off the stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After this, we have three function declarations - &lt;code&gt;fn1()&lt;/code&gt;, &lt;code&gt;fn2()&lt;/code&gt;, and &lt;code&gt;fn3()&lt;/code&gt;. These don't get pushed to the Call Stack as we haven't executed them yet, but memory is allocated to store these functions. The exact location of this memory allocation can vary depending on the JavaScript engine's implementation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When we reach &lt;code&gt;fn3()&lt;/code&gt;, it's pushed onto the Call Stack. Inside &lt;code&gt;fn3()&lt;/code&gt;, we make another call to &lt;code&gt;fn2()&lt;/code&gt;. Following the LIFO principle, &lt;code&gt;fn2()&lt;/code&gt; is pushed onto the Call Stack on top of &lt;code&gt;fn3()&lt;/code&gt;, and its execution starts. Once &lt;code&gt;fn2()&lt;/code&gt; finishes execution, it's popped off the stack, and the control returns back to &lt;code&gt;fn3()&lt;/code&gt;. &lt;code&gt;fn3()&lt;/code&gt; then proceeds with the rest of the execution and gets popped off the stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, control reaches back to the main program, and it moves to the next line - execute &lt;code&gt;fn1()&lt;/code&gt;. &lt;code&gt;fn1()&lt;/code&gt; goes through the same process again. It's pushed onto the stack, and an execution context is created for it. Once it's done executing, it's popped off the stack, and the control reaches back to the main program.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the end, when the script is done executing, &lt;code&gt;main()&lt;/code&gt;(global execution context) is also popped off the stack, and &lt;em&gt;the Call Stack is empty&lt;/em&gt;!&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;JavaScript, being a single-threaded language, can only do one thing at a time. When there's &lt;em&gt;stuff to do&lt;/em&gt; on the Call Stack and JavaScript is busy executing it, it cannot do anything else. This is why it's important not to put long-running tasks on the Call Stack.&lt;/p&gt;

&lt;p&gt;But then how does JavaScript support &lt;code&gt;async&lt;/code&gt; tasks like API calls and &lt;code&gt;setTimeout&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;Let's understand this with another example.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm426smvp6751xh0db5k8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm426smvp6751xh0db5k8.gif" alt="Call Stack and Web APIs" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This example uses &lt;code&gt;setTimeout&lt;/code&gt; to execute a function &lt;em&gt;later&lt;/em&gt;. If you notice, JavaScript didn't wait for 3 seconds before moving on to the next line. Then how does JavaScript know when the timer runs out? It can only do one thing at a time. If it's not counting up to 3 seconds, who is?&lt;/p&gt;

&lt;p&gt;Turns out, JavaScript offloads these kinds of async tasks to the browser via Web APIs.&lt;/p&gt;

&lt;p&gt;When the control reaches the &lt;code&gt;setTimeout&lt;/code&gt;, it gets pushed onto the Call Stack. It tells the browser - &lt;em&gt;Hey, can you remind me to run this &lt;code&gt;fn&lt;/code&gt; after &lt;code&gt;t&lt;/code&gt; milliseconds?&lt;/em&gt; and then continues with the rest of the program. Now, it's the browser's job to keep track of the timer.&lt;/p&gt;

&lt;p&gt;But what happens when the timer runs out?&lt;/p&gt;

&lt;p&gt;Web APIs cannot push anything directly onto the Call Stack. There could be multiple callbacks from &lt;code&gt;setTimeout&lt;/code&gt;s or &lt;code&gt;fetch&lt;/code&gt; calls waiting to be run. If everything gets pushed onto the Call Stack, things will go haywire. You'd see unexpected results, with the Call Stack being hijacked randomly.&lt;/p&gt;

&lt;p&gt;This is where the Task Queue comes in. It is also known as the Macrotask Queue or Callback Queue.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Also, note that the browser can perform multiple tasks in parallel. The underlying libraries are built on multi-threaded languages.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Task Queue
&lt;/h2&gt;

&lt;p&gt;When the timer runs out, the callback function from &lt;code&gt;setTimeout&lt;/code&gt; is pushed into the Task Queue. The Task Queue (also known as the Callback Queue) holds callbacks from Web APIs and various event handlers waiting to be executed.&lt;/p&gt;

&lt;p&gt;Some examples of tasks that go into Task queue:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt; callbacks&lt;/li&gt;
&lt;li&gt;DOM events (like &lt;code&gt;click&lt;/code&gt;, &lt;code&gt;keypress&lt;/code&gt;, etc.)&lt;/li&gt;
&lt;li&gt;AJAX/HTTP requests&lt;/li&gt;
&lt;li&gt;I/O operations (in Node.js)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once the Call Stack is empty, JavaScript picks up the tasks from the Task Queue and pushes them onto the Call Stack for execution.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjn5kq6souqjpysgasodk.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjn5kq6souqjpysgasodk.gif" alt="Call Stack, Web APIs and Task Queue" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So far, we've covered the Call Stack, Web APIs, and Task Queue. There's one final piece left to complete the puzzle, and it's an important one - the Microtask Queue.&lt;/p&gt;

&lt;p&gt;Understanding the difference between these queues is crucial for grasping how JavaScript prioritizes and executes asynchronous operations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Microtask Queue
&lt;/h2&gt;

&lt;p&gt;Not everything gets pushed to the Task Queue. Modern APIs that support promises get pushed to the Microtask Queue. This queue has higher priority than the Task Queue.&lt;/p&gt;

&lt;p&gt;Here's a list of items that use the Microtask Queue:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Promise handler callbacks (&lt;code&gt;then(callback)&lt;/code&gt;, &lt;code&gt;catch(callback)&lt;/code&gt;, and &lt;code&gt;finally(callback)&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Execution of &lt;code&gt;async&lt;/code&gt; function bodies following &lt;code&gt;await&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;queueMicrotask&lt;/code&gt; callbacks&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;MutationObserver&lt;/code&gt; callbacks&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once the Call Stack is empty, before checking the Task Queue, JavaScript checks the Microtask Queue. It executes all the callbacks(aka microtasks) available in the Microtask Queue and then moves to the Task Queue.&lt;/p&gt;

&lt;p&gt;Here's an example to help you visualize it:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmy3zp0i70h19eaf7lbz1.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmy3zp0i70h19eaf7lbz1.gif" alt="Call Stack, Web APIs, Task Queue and Microtask Queue" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above, there's an additional &lt;code&gt;Promise&lt;/code&gt;-based &lt;code&gt;fetch&lt;/code&gt; call. When the server responds, its callback will be pushed to the Microtask Queue.&lt;/p&gt;

&lt;p&gt;When the Call Stack is empty, the Microtask Queue is checked. If we have the response callback ready, it's pushed onto the Call Stack. Once the Microtask Queue is empty, the Task Queue is checked. If we have the &lt;code&gt;setTimeout&lt;/code&gt;'s callback ready in the Task queue, it's pushed onto the Call Stack.&lt;/p&gt;

&lt;p&gt;If we hadn't received the API response in time and the Microtask Queue was empty, then &lt;code&gt;setTimeout&lt;/code&gt;'s callback would have been executed first.&lt;/p&gt;

&lt;p&gt;Key points about these two queues:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Tasks from both queues are only picked once the Call Stack is empty.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The Microtask Queue has high priority, so it's checked first. &lt;em&gt;All the tasks&lt;/em&gt; available in the Microtask Queue are executed before the Task Queue is checked.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;After each task execution from the Task Queue, the Microtask Queue is checked again. It could be the case that one of the tasks from the Task Queue led to the insertion of a callback in the Microtask Queue. Being high priority, it must be checked frequently.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Remember: &lt;strong&gt;Only one&lt;/strong&gt; item is executed from the Task Queue before the Microtask Queue is checked again, whereas &lt;strong&gt;all the items&lt;/strong&gt; from the Microtask Queue are executed before checking anything else. The Microtask Queue must be emptied when control comes to it!&lt;/p&gt;

&lt;h2&gt;
  
  
  The Event Loop: Tying It All Together
&lt;/h2&gt;

&lt;p&gt;All the mechanisms we've discussed - the Call Stack, Web APIs, Task Queue, and Microtask Queue - are orchestrated by what's known as the Event Loop.&lt;/p&gt;

&lt;p&gt;The Event Loop is the heart of JavaScript's concurrency model. It continuously checks the Call Stack and, when it's empty, looks at the Microtask Queue and Task Queue. It's responsible for moving callbacks from these queues to the Call Stack for execution, maintaining the order and priority we've discussed.&lt;/p&gt;

&lt;p&gt;This process allows JavaScript, a single-threaded language, to handle asynchronous operations efficiently, enabling non-blocking I/O operations and creating the illusion of multi-threading.&lt;/p&gt;

&lt;p&gt;Understanding the Event Loop is crucial for writing efficient and responsive JavaScript code, whether you're working on browser-based applications or server-side with Node.js.&lt;/p&gt;




&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;JavaScript is single-threaded but can handle asynchronous operations. The Event Loop creates the illusion of multi-threading in JavaScript.&lt;/li&gt;
&lt;li&gt;The JavaScript Engine consists of the Heap (for memory allocation) and the Call Stack.&lt;/li&gt;
&lt;li&gt;The Call Stack follows LIFO (Last In, First Out) structure for function execution.&lt;/li&gt;
&lt;li&gt;Web APIs (like &lt;code&gt;setTimeout&lt;/code&gt;, &lt;code&gt;fetch&lt;/code&gt;) are provided by the browser, not JavaScript itself.&lt;/li&gt;
&lt;li&gt;Web APIs offload asynchronous tasks from the Call Stack to enable non-blocking execution.&lt;/li&gt;
&lt;li&gt;The Task Queue (or Callback Queue) holds callbacks from Web APIs (e.g., &lt;code&gt;setTimeout&lt;/code&gt;, DOM events).&lt;/li&gt;
&lt;li&gt;The Microtask Queue has higher priority and contains &lt;code&gt;Promise&lt;/code&gt; callbacks and &lt;code&gt;queueMicrotask&lt;/code&gt; callbacks.&lt;/li&gt;
&lt;li&gt;The Event Loop continuously monitors the Call Stack and both queues.&lt;/li&gt;
&lt;li&gt;When the Call Stack is empty, the Event Loop first checks and empties the Microtask Queue.&lt;/li&gt;
&lt;li&gt;After Microtasks, the Event Loop takes one task from the Task Queue and pushes it to the Call Stack. Then it repeats the process in point 9 until both Microtask Queue and Task queue are empty.&lt;/li&gt;
&lt;li&gt;Microtasks always execute before the next Task(from Task/Callback queue), ensuring &lt;code&gt;Promise&lt;/code&gt; resolutions are handled promptly.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Resources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=cCOL7MC4Pl0" rel="noopener noreferrer"&gt;Jake Archibald on Event Loop&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ" rel="noopener noreferrer"&gt;What the heck is the event loop anyway? | Philip Roberts | JSConf EU&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>frontend</category>
      <category>interview</category>
    </item>
    <item>
      <title>What is JavaScript? One Definition to Cover It All.</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Thu, 15 Aug 2024 06:21:43 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/what-is-javascript-one-definition-to-cover-it-all-43l2</link>
      <guid>https://forem.com/thesanjeevsharma/what-is-javascript-one-definition-to-cover-it-all-43l2</guid>
      <description>&lt;p&gt;This might or might not get asked in an Interview but trust me once you read this you'll understand JS jargons much better. (Brownie points for using this during an Interview).&lt;/p&gt;

&lt;p&gt;This is question #3 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider joining the waitlist on &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;JavaScript is a single-threaded, dynamically typed, interpreted programming language that supports multiple paradigms including object-oriented, functional, and imperative styles. It features prototype-based object orientation and an event-driven architecture.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the nerdy definition of JavaScript. But what does each term mean? Let's find out.&lt;/p&gt;

&lt;h3&gt;
  
  
  Single-threaded
&lt;/h3&gt;

&lt;p&gt;JavaScript is a Single-threaded language meaning it only has one main thread of execution. It also means that it has a single call stack. When a function call is made, it's added to the top of the call stack. Once it's done executing, it's popped off the stack and the control moves to the next function in the call stack. Executing tasks sequentially is fundamental to JavaScript's nature but it does provide APIs to execute asynchronous operations(fetch and setTimeout are some examples).&lt;/p&gt;

&lt;h3&gt;
  
  
  Dynamically Typed
&lt;/h3&gt;

&lt;p&gt;In JavaScript, variables are not explicitly declared with types. Types are associated with values and not variables as they are inferred at runtime. Types can also change during the lifecycle of a program. This feature makes JS flexible but it can be susceptible to type-related errors. Tools like TypeScript help in adding static types during development but it is eventually compiled to JS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Interpreted Programming Language
&lt;/h3&gt;

&lt;p&gt;Unlike compiled languages such as Java, JavaScript is not compiled into machine code before execution. Instead the code is read, interpreted, and executed line by line at runtime. However, to improve performance, modern JavaScript engines use Just-In-Time(JIT) compilation which compiles chunks of code on-the-fly. This approach improves execution speed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Object-oriented
&lt;/h3&gt;

&lt;p&gt;This programming paradigm organizes code into Objects, which are instances of classes or prototypes. The &lt;code&gt;class&lt;/code&gt; keyword was introduced in ES6 for syntactic sugar. Under the hood, classes in JavaScript still use prototypes. This implementation of OOP is unique to JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Functional
&lt;/h3&gt;

&lt;p&gt;It is a programming paradigm which promotes writing declarative code by emphasizing the use of functions. Some of the key concepts are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pure functions: Functions that always produce the same output for given inputs and have no side effects.&lt;/li&gt;
&lt;li&gt;Higher-order functions: Functions that can take other functions as arguments or return them as results.&lt;/li&gt;
&lt;li&gt;Immutability: Treating data as immutable, though JavaScript doesn't enforce this by default.&lt;/li&gt;
&lt;li&gt;First-class functions: Functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments, or returned from other functions.&lt;/li&gt;
&lt;li&gt;Function composition: Building complex functionality by combining simpler functions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;JavaScript supports these functional programming concepts alongside its other paradigms, allowing developers to use functional techniques where appropriate.&lt;/p&gt;

&lt;h3&gt;
  
  
  Imperative
&lt;/h3&gt;

&lt;p&gt;Imperative programming is a paradigm where the code explicitly describes the sequence of steps that the program must take to reach the desired state. JavaScript fully supports all necessary constructs like variables, loops, conditionals, and operators which are required for writing imperative code. This approach allows for precise control over the program's execution flow. It is often used for implementing algorithms and managing complex state changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Prototype-based Orientation
&lt;/h3&gt;

&lt;p&gt;JavaScript uses a prototype-based object model, which is a form of object-oriented programming where objects are the primary entities. Unlike class-based languages, JavaScript uses prototypes to implement inheritance and share properties and methods between objects.&lt;/p&gt;

&lt;p&gt;Key aspects of prototype-based orientation in JavaScript include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Object creation: Objects can be created directly without defining a class first.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Prototype chain: Each object has a link to another object called its prototype. If a property or method isn't found on an object, JavaScript looks for it in the prototype, then the prototype's prototype, and so on.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inheritance: Objects can inherit properties and methods from other objects through their prototype chain.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This prototype-based system allows for powerful and flexible object-oriented programming.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event-driven Architecture
&lt;/h3&gt;

&lt;p&gt;JavaScript's event-based architecture is a programming approach where the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs. This is fundamental to how JavaScript interacts with web browsers and handles asynchronous operations.&lt;/p&gt;

&lt;p&gt;Key aspects of JavaScript's event-based architecture include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Event listeners: Functions that "listen" for specific events and execute when those events occur.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Event loop: A continuous process that checks for and dispatches events to their listeners.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Asynchronous programming: Allows code to run without blocking the main thread, crucial for responsive web applications.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This architecture enables JavaScript to handle user interactions, API calls, timers, and other asynchronous operations efficiently, making it well-suited for creating interactive web applications.&lt;/p&gt;

&lt;p&gt;All these concepts combined make JavaScript a versatile language which can be used on a variety of platforms like Web, Mobile, Server, and AR.&lt;/p&gt;




&lt;h2&gt;
  
  
  Notes
&lt;/h2&gt;

&lt;p&gt;For your interview, remember this definition:&lt;/p&gt;

&lt;p&gt;JavaScript is a single-threaded, dynamically typed and interpreted-compiled language. It is a cross-platform language but mainly used on web for adding interactivity to pages.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;Frontend Camp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://medium.com/swlh/what-does-it-mean-by-javascript-is-single-threaded-language-f4130645d8a9" rel="noopener noreferrer"&gt;What does it mean by Javascript is single threaded language&lt;/a&gt;&lt;br&gt;
&lt;a href="https://stackoverflow.com/a/3265602" rel="noopener noreferrer"&gt;Interpreted vs Compiled Programming Languages&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>frontend</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Debouncing and Throttling</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Fri, 09 Aug 2024 10:27:42 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/debouncing-and-throttling-4alb</link>
      <guid>https://forem.com/thesanjeevsharma/debouncing-and-throttling-4alb</guid>
      <description>&lt;p&gt;Another one among the popular frontend interview questions. It tests interviewees knowledge on JS, Performance and FE System Design.&lt;/p&gt;

&lt;p&gt;This is question #2 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;FrontendCamp&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;Debouncing and Throttling work on the same principle - delay stuff -  but still have very different approach and use cases.&lt;/p&gt;

&lt;p&gt;Both the concepts are useful for developing a performant application.  Almost all the websites you visit on a daily basis use Debouncing and Throttling in some way or the other.&lt;/p&gt;

&lt;h3&gt;
  
  
  Debouncing
&lt;/h3&gt;

&lt;p&gt;A well known use case of debouncing is a typeahead(or autocomplete).&lt;/p&gt;

&lt;p&gt;Imagine you are building a search feature for an E-commerce website that has thousands of products. When a user tries to search for something, your app would make an API call to fetch all the products that match the user's query string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleKeyDown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
 &lt;span class="c1"&gt;// set the result to a state and then render on UI&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Input&lt;/span&gt; &lt;span class="nx"&gt;onKeyDown&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleKeyDown&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach looks fine but it has some issues:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;You're making an API call on each key press event. If a user types 15 characters, that's 15 API calls for a single user. This would never scale.&lt;/li&gt;
&lt;li&gt;When the result from these 15 API calls arrives, you only need the last one. Result from previous 14 calls will be discarded. It eats up a lot of user's bandwidth and users on slow network will see a significant delay.&lt;/li&gt;
&lt;li&gt;On the UI, these 15 API calls will trigger a re-render. It will make the component laggy.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The solution to these problems is &lt;code&gt;Debouncing&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The basic idea is to wait until the user stops typing. We'll delay the API call.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;debounce&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;timerId&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;timerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;clearTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;timerId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;};&lt;/span&gt;
  &lt;span class="nx"&gt;timerId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nx"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleKeyDown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
 &lt;span class="c1"&gt;// set the result to a state and then render on UI&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Input&lt;/span&gt; &lt;span class="nx"&gt;onKeyDown&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;debounce&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;handleKeyDown&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt; &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We've extended our existing code to make use of debouncing.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;debounce&lt;/code&gt; function is generic utility function that takes two arguments:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;fn&lt;/code&gt;: The function call that is supposed to be delayed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;delay&lt;/code&gt;: The delay in milliseconds.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Inside the function, we use &lt;code&gt;setTimeout&lt;/code&gt; to delay the actual function(&lt;code&gt;fn&lt;/code&gt;) call. If the &lt;code&gt;fn&lt;/code&gt; is called again before timer runs out, the timer resets.&lt;/p&gt;

&lt;p&gt;With our updated implementation, even if the user types 15 characters we would only make 1 API call(assuming each key press takes less than 500 milliseconds). This solves all the issues we had when we started building this feature.&lt;/p&gt;

&lt;p&gt;In a production codebase, you won't have to code your own &lt;code&gt;debounce&lt;/code&gt; utility function. Chances are your company already uses a JS utility library like &lt;a href="https://www.lodashjs.com/docs/lodash.debounce/" rel="noopener noreferrer"&gt;lodash&lt;/a&gt; that has these methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  Throttling
&lt;/h3&gt;

&lt;p&gt;Well, Debouncing is great for performance but there a some scenarios where we don't want to wait for &lt;code&gt;x&lt;/code&gt; seconds before being notified of a change.&lt;/p&gt;

&lt;p&gt;Imaging you're building a collaborative workspace like Google Docs or Figma. One of the key features is a user should be aware of changes made my other users in real time.&lt;/p&gt;

&lt;p&gt;So far we only know of two approaches:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Noob approach: Any time a user moves their mouse pointer or types something, make an API call. You already know how bad it can get.&lt;/li&gt;
&lt;li&gt;The Debouncing approach: It does solve the performance side of things but from a UX perspective it's terrible. Your coworker might write a 300 words paragraph and you only get notified once in the end. Is it still considered real-time?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is where &lt;code&gt;Throttling&lt;/code&gt; comes in. It's right in middle of the two approaches mentioned above. The basic idea is - notify on periodic intervals - not in the end and not on each key press, but periodically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;throttle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;time&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;remainingTime&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;time&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;now&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;remainingTime&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleKeyDown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="c1"&gt;// save it DB and also notify other peers&lt;/span&gt;
 &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Editor&lt;/span&gt; &lt;span class="nx"&gt;onKeyDown&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;throttle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;handleKeyDown&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt; &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We've modified our existing code to utilise &lt;code&gt;throttle&lt;/code&gt; function. It takes two arguments:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;fn&lt;/code&gt;: The actual function to throttle.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;time&lt;/code&gt;: The interval after which the function is allowed to execute.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The implementation is straight-forward. We store the time when the function was last called in &lt;code&gt;lastCalledAt&lt;/code&gt;. Next time, when a function call is made, we check if &lt;code&gt;time&lt;/code&gt; has passed and only then we execute &lt;code&gt;fn&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We're almost there, but this implementation has a bug. What if last function call with some data is made within the &lt;code&gt;time&lt;/code&gt; interval and no call is made after that. With our current implementation, we will lose some data.&lt;/p&gt;

&lt;p&gt;To fix this, we'll store the arguments in another variable and initiate a timeout to be called later if no event is received.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;throttle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;time&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;lastArgs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;timeoutId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;remainingTime&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;time&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;now&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;remainingTime&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="c1"&gt;// call immediately&lt;/span&gt;
   &lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;now&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;timeoutId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
     &lt;span class="nf"&gt;clearTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;timeoutId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
     &lt;span class="nx"&gt;timeoutId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// call later if no event is received&lt;/span&gt;
    &lt;span class="nx"&gt;lastArgs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;timeoutId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;timeoutId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;lastArgs&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;lastCalledAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nx"&gt;lastArgs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nx"&gt;timeoutId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="nx"&gt;remainingTime&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This updated implementation makes sure we don't miss out on any data.&lt;/p&gt;

&lt;p&gt;Lodash also provides a &lt;a href="https://www.lodashjs.com/docs/lodash.throttle/" rel="noopener noreferrer"&gt;throttle&lt;/a&gt; utility function.&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Debouncing and Throttling are performance optimization techniques.&lt;/li&gt;
&lt;li&gt;Both of these work on a similar principle - delay things.&lt;/li&gt;
&lt;li&gt;Debounce waits for &lt;code&gt;t&lt;/code&gt; after the last event is received whereas Throttling executes the &lt;code&gt;fn&lt;/code&gt; periodically in &lt;code&gt;t&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;Debouncing is used in search features and Throttling is used in Real-time apps(not limited to these).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://frontendcamp.in/open-questions/debounce-and-throttle" rel="noopener noreferrer"&gt;FrontendCamp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://lodashjs.com" rel="noopener noreferrer"&gt;lodash&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>performance</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Understanding async and defer</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Thu, 08 Aug 2024 13:16:12 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/understanding-async-and-defer-11fn</link>
      <guid>https://forem.com/thesanjeevsharma/understanding-async-and-defer-11fn</guid>
      <description>&lt;p&gt;This is one of the popular frontend interview questions. It tests interviewees knowledge on HTML, JS and Performance.&lt;/p&gt;

&lt;p&gt;This is question #1 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on &lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;FrontendCamp&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;The &lt;code&gt;script&lt;/code&gt; tag is used to add JavaScript to an HTML page. It could be an inline script or an external script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;body&amp;gt;&lt;/span&gt;
  &lt;span class="c"&gt;&amp;lt;!-- Some code before it --&amp;gt;&lt;/span&gt;

  &lt;span class="nt"&gt;&amp;lt;script&amp;gt;&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;This is an inline script.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nt"&gt;&amp;lt;/script&amp;gt;&lt;/span&gt;

  &lt;span class="nt"&gt;&amp;lt;script &lt;/span&gt;&lt;span class="na"&gt;src=&lt;/span&gt;&lt;span class="s"&gt;"https://example.com/external-script.js"&lt;/span&gt; &lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;

  &lt;span class="o"&gt;&amp;lt;!--&lt;/span&gt; &lt;span class="nx"&gt;Some&lt;/span&gt; &lt;span class="nx"&gt;code&lt;/span&gt; &lt;span class="nx"&gt;after&lt;/span&gt; &lt;span class="nx"&gt;it&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/body&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While parsing the HTML, if browser encounters a script tag it will stop HTML parsing and start executing the JS script. If it's inline it will start with execution straight away but if it's an external script, it will be downloaded and then executed.&lt;/p&gt;

&lt;p&gt;During this time, when JS script is being downloaded and executed, HTML parsing is blocked. It can only resume once the browser is done with executing the JS script.&lt;/p&gt;

&lt;p&gt;Do you see what's wrong here? This will cause performance issues for the end user. If we have a lot of scripts or any script takes a lot of time to execute, user won't see the content of the page for a long time.&lt;/p&gt;

&lt;p&gt;To solve exactly this, we have two attributes: &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;defer&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;async&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;If the &lt;code&gt;async&lt;/code&gt; attribute is present, the script will be downloaded in parallel to parsing HTML and executed as soon as it is available.&lt;/p&gt;

&lt;p&gt;If multiple scripts use the &lt;code&gt;async&lt;/code&gt; attribute, the order of execution might be different than the order in which they appear in the HTML. The script that is available first will be executed first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;body&amp;gt;&lt;/span&gt;
  &lt;span class="c"&gt;&amp;lt;!-- Some code before it --&amp;gt;&lt;/span&gt;

  &lt;span class="nt"&gt;&amp;lt;script &lt;/span&gt;&lt;span class="na"&gt;async&lt;/span&gt; &lt;span class="na"&gt;src=&lt;/span&gt;&lt;span class="s"&gt;"https://example.com/external-script.js"&lt;/span&gt; &lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;

  &lt;span class="o"&gt;&amp;lt;!--&lt;/span&gt; &lt;span class="nx"&gt;Some&lt;/span&gt; &lt;span class="nx"&gt;code&lt;/span&gt; &lt;span class="nx"&gt;after&lt;/span&gt; &lt;span class="nx"&gt;it&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/body&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;code&gt;defer&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;If the &lt;code&gt;defer&lt;/code&gt; attribute is present, the script will be downloaded in parallel to HTML parsing(just like &lt;code&gt;async&lt;/code&gt;) but executed after HTML parsing is finished and before firing &lt;code&gt;DOMContentLoaded&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If multiple scripts use the &lt;code&gt;defer&lt;/code&gt; attribute, the order of execution will be maintained, unlike &lt;code&gt;async&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;body&amp;gt;&lt;/span&gt;
  &lt;span class="c"&gt;&amp;lt;!-- Some code before it --&amp;gt;&lt;/span&gt;

  &lt;span class="nt"&gt;&amp;lt;script &lt;/span&gt;&lt;span class="na"&gt;defer&lt;/span&gt; &lt;span class="na"&gt;src=&lt;/span&gt;&lt;span class="s"&gt;"https://example.com/external-script.js"&lt;/span&gt; &lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;

  &lt;span class="o"&gt;&amp;lt;!--&lt;/span&gt; &lt;span class="nx"&gt;Some&lt;/span&gt; &lt;span class="nx"&gt;code&lt;/span&gt; &lt;span class="nx"&gt;after&lt;/span&gt; &lt;span class="nx"&gt;it&lt;/span&gt; &lt;span class="o"&gt;--&amp;gt;&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/body&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Both &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;defer&lt;/code&gt; download script without blocking HTML parsing.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;async&lt;/code&gt; script will be executed as soon as it's available. It could potentially block HTML parsing.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;defer&lt;/code&gt; script will only be executed once HTML parsing is complete but before firing &lt;code&gt;DOMContentLoaded&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;async&lt;/code&gt;, if the order of execution doesn't matter and the script doesn't modify the DOM.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;defer&lt;/code&gt;, if the order is execution is important or the script modifies the DOM.&lt;/li&gt;
&lt;li&gt;Also, note that these attributes &lt;strong&gt;don't work on inline scripts&lt;/strong&gt; i.e. scripts without &lt;code&gt;src&lt;/code&gt; attribute.&lt;/li&gt;
&lt;li&gt;If both &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;defer&lt;/code&gt; are added, &lt;code&gt;async&lt;/code&gt; takes precedence.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script" rel="noopener noreferrer"&gt;MDN: The script element&lt;/a&gt;&lt;br&gt;
&lt;a href="https://frontendcamp.in" rel="noopener noreferrer"&gt;FrontendCamp&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>performance</category>
      <category>html</category>
    </item>
    <item>
      <title>Introducing DEV AI: Your Tech Blogging Sidekick</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Sat, 13 Apr 2024 17:01:31 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/introducing-dev-ai-your-tech-blogging-sidekick-48ii</link>
      <guid>https://forem.com/thesanjeevsharma/introducing-dev-ai-your-tech-blogging-sidekick-48ii</guid>
      <description>&lt;p&gt;&lt;em&gt;This is a submission for the &lt;a href="https://dev.to/devteam/join-us-for-the-cloudflare-ai-challenge-3000-in-prizes-5f99"&gt;Cloudflare AI Challenge&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What I Built
&lt;/h2&gt;

&lt;p&gt;Presenting &lt;strong&gt;DEV AI&lt;/strong&gt; ✨, an AI assistant for the DEV platform. The app caters to two categories of users: &lt;em&gt;Readers&lt;/em&gt; and &lt;em&gt;Creators&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;For readers 👀: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It can summarize an article for you.&lt;/li&gt;
&lt;li&gt;It can translate the summarization into your preferred language.&lt;/li&gt;
&lt;li&gt;It can do a sentiment analysis on the article.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For creators ✍️:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It can generate a cover image for you.&lt;/li&gt;
&lt;li&gt;It can create a structured plan for your next article.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://dev-to-ai.pages.dev" class="ltag_cta ltag_cta--branded" rel="noopener noreferrer"&gt;🔗 DEV AI&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;Reader mode&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-ai.pages.dev%2Freader-mode.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-ai.pages.dev%2Freader-mode.jpeg" alt="Reader mode" width="800" height="526"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Creator mode&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-ai.pages.dev%2Fcreator-mode.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-ai.pages.dev%2Fcreator-mode.jpeg" alt="Creator mode" width="800" height="526"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  My Code
&lt;/h2&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fassets.dev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/thesanjeevsharma" rel="noopener noreferrer"&gt;
        thesanjeevsharma
      &lt;/a&gt; / &lt;a href="https://github.com/thesanjeevsharma/dev-to-ai" rel="noopener noreferrer"&gt;
        dev-to-ai
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Unofficial DevTo AI Assistant
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;DEV AI&lt;/h1&gt;

&lt;/div&gt;
&lt;blockquote&gt;
&lt;p&gt;Unofficial AI app for DEV readers and creators, created as part of &lt;a href="https://dev.to/challenges/cloudflare" rel="nofollow"&gt;Cloudflare AI x DEV challenge&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Demo&lt;/h2&gt;

&lt;/div&gt;
&lt;p&gt;🔗 &lt;a href="https://dev-to-ai.pages.dev" rel="nofollow noopener noreferrer"&gt;https://dev-to-ai.pages.dev&lt;/a&gt;&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Features&lt;/h2&gt;

&lt;/div&gt;
&lt;p&gt;The app runs in two modes: &lt;code&gt;Creator&lt;/code&gt; and &lt;code&gt;Reader&lt;/code&gt; mode.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Creator mode&lt;/strong&gt;: Let's you generate a cover image and action plan for your next article.
&lt;a rel="noopener noreferrer nofollow" href="https://camo.githubusercontent.com/351e87c065e2202d235c8307f1f4096904ad389e000751aad0d373c6929e0716/68747470733a2f2f6465762d746f2d61692e70616765732e6465762f63726561746f722d6d6f64652e6a706567"&gt;&lt;img src="https://camo.githubusercontent.com/351e87c065e2202d235c8307f1f4096904ad389e000751aad0d373c6929e0716/68747470733a2f2f6465762d746f2d61692e70616765732e6465762f63726561746f722d6d6f64652e6a706567" alt="Creator mode"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Reader mode&lt;/strong&gt;: Let's you summarize and translate an article. It also provides a sentiment analysis of the article.
&lt;a rel="noopener noreferrer nofollow" href="https://camo.githubusercontent.com/bbe9e8963a610a261b5ece6bd635f09a9f68db55f13828aa03516cb113711947/68747470733a2f2f6465762d746f2d61692e70616765732e6465762f7265616465722d6d6f64652e6a706567"&gt;&lt;img src="https://camo.githubusercontent.com/bbe9e8963a610a261b5ece6bd635f09a9f68db55f13828aa03516cb113711947/68747470733a2f2f6465762d746f2d61692e70616765732e6465762f7265616465722d6d6f64652e6a706567" alt="Reader mode"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Installation Steps&lt;/h2&gt;

&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;Make sure you have the required env variables set from &lt;code&gt;.env.example&lt;/code&gt; file.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="snippet-clipboard-content notranslate position-relative overflow-auto"&gt;&lt;pre class="notranslate"&gt;&lt;code&gt;NEXT_APP_DEV_TO_API=https://dev.to/api/articles
CF_WORKER_AI=https://api.cloudflare.com/client/v4/accounts/&amp;lt;ACCOUNT_ID&amp;gt;/ai/run/@cf
CF_TOKEN=&amp;lt;TOKEN&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Replace &lt;code&gt;ACCOUNT_ID&lt;/code&gt; and &lt;code&gt;TOKEN&lt;/code&gt; with the value you get from Cloudflare. Please generate the token with &lt;code&gt;Workers AI&lt;/code&gt; &lt;code&gt;read&lt;/code&gt; and &lt;code&gt;edit&lt;/code&gt; access.&lt;/p&gt;
&lt;ol start="2"&gt;
&lt;li&gt;Run &lt;code&gt;npm i&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;npm run dev&lt;/code&gt; to run the project locally&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;



&lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/thesanjeevsharma/dev-to-ai" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;
 

&lt;h2&gt;
  
  
  Journey
&lt;/h2&gt;

&lt;p&gt;Initially, I was planning to build a summarizer for YouTube videos but YT already does that. Also, the same idea has been implemented by quite a few devs. It wasn't unique and it would have been a throwaway project for me.&lt;/p&gt;

&lt;p&gt;Then while browsing DEV, I got this idea of summarizing articles instead. I know it's been built too, but not specifically for DEV. I added translation and sentiment analysis as well to take it a step further.&lt;/p&gt;

&lt;p&gt;Later on, I extended the app to have a &lt;em&gt;Creator mode&lt;/em&gt;. I've used ChatGPT countless times whenever I've hit the writers block, which is why I wanted to build something to help writers like me. I also spend a lot of time trying to find the right cover image for my article, hence decided to add an Image generation feature as well.&lt;/p&gt;

&lt;p&gt;This is my first project with an AI integration. Now, I've got some idea about how these models work from an API perspective and I can explore further in this area. It was a fun challenge and filled with lots of learning.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Future plans:&lt;/em&gt; I plan to keep the app running and make gradual updates to it(Hopefully, these AI models will keep getting better). It's actually a resume-worthy project. ✨  &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Techstack:&lt;/em&gt; NextJS, TailwindCSS and Cloudflare Pages.&lt;/p&gt;

&lt;p&gt;Models used:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://developers.cloudflare.com/workers-ai/models/bart-large-cnn/" rel="noopener noreferrer"&gt;@cf/facebook/bart-large-cnn&lt;/a&gt; for summarizing. It's in beta right now, therefore results aren't that great. I tried switching to other text generation models but the input text is limited on those. I guess I'll have to stick with this one for now.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developers.cloudflare.com/workers-ai/models/m2m100-1.2b/" rel="noopener noreferrer"&gt;@cf/meta/m2m100-1.2b&lt;/a&gt; for translation.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developers.cloudflare.com/workers-ai/models/distilbert-sst-2-int8/" rel="noopener noreferrer"&gt;@cf/huggingface/distilbert-sst-2-int8&lt;/a&gt; for sentiment analysis.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developers.cloudflare.com/workers-ai/models/stable-diffusion-xl-base-1.0/" rel="noopener noreferrer"&gt;@cf/stabilityai/stable-diffusion-xl-base-1.0&lt;/a&gt; for generating the cover image based on description provided by the user.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developers.cloudflare.com/workers-ai/models/llama-2-7b-chat-fp16/" rel="noopener noreferrer"&gt;@cf/meta/llama-2-7b-chat-fp16&lt;/a&gt; for creating a writing plan for article based on the description provided.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Multiple Models and/or Triple Task Types&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes, I've used 5 models as stated above.&lt;/p&gt;

</description>
      <category>cloudflarechallenge</category>
      <category>devchallenge</category>
      <category>ai</category>
      <category>writing</category>
    </item>
    <item>
      <title>Introduction to NGINX</title>
      <dc:creator>Sanjeev Sharma</dc:creator>
      <pubDate>Tue, 19 Dec 2023 04:46:44 +0000</pubDate>
      <link>https://forem.com/thesanjeevsharma/introduction-to-nginx-213b</link>
      <guid>https://forem.com/thesanjeevsharma/introduction-to-nginx-213b</guid>
      <description>&lt;p&gt;NGINX, pronounced as 'engine-x', is an open-source web server that is mainly used for Reverse proxy, Caching, and Load balancing. &lt;/p&gt;

&lt;p&gt;If you're into web dev, at some point in your career you might have to work with NGINX. This article will help you get started with NGINX. By the end, you'll be able to setup your own NGINX web server. You'll also understand terms like load balancing and reverse proxy.&lt;/p&gt;




&lt;h3&gt;
  
  
  Why NGINX?
&lt;/h3&gt;

&lt;p&gt;NGINX is widely used for serving web content. It is known for its high performance, stability, and efficiency, making it a popular choice for various web applications and websites.&lt;/p&gt;

&lt;p&gt;Some key features of NGINX are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Web Server&lt;/strong&gt; 🤖: It can serve static content(such as HTML, CSS and images) directly to clients, making it efficient for delivering web pages.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reverse Proxy&lt;/strong&gt; ⏩: It can act a reverse proxy by forwarding client's requests to other servers. It is a commonly used practice for security and scalability.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Load Balancer&lt;/strong&gt; ⚖️: It can route incoming traffic to different server instances ensuring optimal resource utilization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SSL/TLS Termination&lt;/strong&gt; 🔐: It can handle SSL/TLS termination, encrypting and decrypting data between clients and servers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Performance Optimization&lt;/strong&gt; ⚡️: It is designed to be lightweight and efficient, capable of handling a large number of concurrent connections with low resource usage.&lt;/li&gt;
&lt;/ol&gt;




&lt;h3&gt;
  
  
  Installation
&lt;/h3&gt;

&lt;h5&gt;
  
  
  Ubuntu/Debian
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo &lt;/span&gt;apt update
&lt;span class="nb"&gt;sudo &lt;/span&gt;apt &lt;span class="nb"&gt;install &lt;/span&gt;nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installation, NGINX will automatically start in the background. To check the status, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;sudo &lt;/span&gt;systemctl status nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  MacOS
&lt;/h5&gt;

&lt;p&gt;We can install it using brew&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;brew &lt;span class="nb"&gt;install &lt;/span&gt;nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installation, you can run it using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;brew services start nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Windows
&lt;/h5&gt;

&lt;ol&gt;
&lt;li&gt;Download the latest stable version of NGINX from the official website: &lt;a href="https://nginx.org/en/download.html" rel="noopener noreferrer"&gt;NGINX Download&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Extract the downloaded zip file to a location of your choice.&lt;/li&gt;
&lt;li&gt;Navigate to the NGINX directory and run &lt;code&gt;nginx.exe&lt;/code&gt;. NGINX should start.&lt;/li&gt;
&lt;/ol&gt;




&lt;h3&gt;
  
  
  Configuration
&lt;/h3&gt;

&lt;p&gt;To find the configuration file, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;nginx &lt;span class="nt"&gt;-t&lt;/span&gt;

nginx: the configuration file /opt/homebrew/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /opt/homebrew/etc/nginx/nginx.conf &lt;span class="nb"&gt;test &lt;/span&gt;is successful
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command tests the configuration file for syntax errors and typos, without applying it. It will also reveal the path to the main configuration file.&lt;/p&gt;

&lt;p&gt;You can either edit this file directly or create a new one to follow along.&lt;/p&gt;

&lt;h4&gt;
  
  
  Serving HTML
&lt;/h4&gt;

&lt;p&gt;If you check the &lt;code&gt;nginx.conf&lt;/code&gt; file, you'll see a lot of blocks wrapped in &lt;code&gt;{}&lt;/code&gt; and a lot of key-value pairs inside these blocks.&lt;/p&gt;

&lt;p&gt;These blocks are known as &lt;strong&gt;contexts&lt;/strong&gt; and the key-value pairs are known as &lt;strong&gt;directives&lt;/strong&gt; for that context.&lt;/p&gt;

&lt;p&gt;We'll clear the file and start from scratch. Your &lt;code&gt;nginx.conf&lt;/code&gt; should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen 8080&lt;span class="p"&gt;;&lt;/span&gt;
        root /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You only need &lt;code&gt;events&lt;/code&gt; and &lt;code&gt;http&lt;/code&gt; contexts to successfully load a configuration. Inside &lt;code&gt;http&lt;/code&gt;, we have the &lt;code&gt;server&lt;/code&gt; context that has the configuration for our web server.&lt;/p&gt;

&lt;p&gt;It tells the server to &lt;code&gt;listen&lt;/code&gt; on port &lt;code&gt;8080&lt;/code&gt; and set &lt;code&gt;root&lt;/code&gt; for serving files as &lt;code&gt;/Users/syfe/Desktop/tutorials/nginx-test/html&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Inside the &lt;code&gt;html&lt;/code&gt; directory, we'll create an &lt;code&gt;index.html&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;html&lt;/span&gt; &lt;span class="na"&gt;lang=&lt;/span&gt;&lt;span class="s"&gt;"en"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;head&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;meta&lt;/span&gt; &lt;span class="na"&gt;charset=&lt;/span&gt;&lt;span class="s"&gt;"UTF-8"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;meta&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"viewport"&lt;/span&gt; &lt;span class="na"&gt;content=&lt;/span&gt;&lt;span class="s"&gt;"width=device-width, initial-scale=1.0"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;title&amp;gt;&lt;/span&gt;Document&lt;span class="nt"&gt;&amp;lt;/title&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/head&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;body&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;h1&amp;gt;&lt;/span&gt;Hello, world!&lt;span class="nt"&gt;&amp;lt;/h1&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/body&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;/html&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is how directory structure looks currently.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fipipi48kr2usfaqc7cb3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fipipi48kr2usfaqc7cb3.png" alt="Directory structure" width="556" height="160"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you created a new conf file, you can load it by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;nginx &lt;span class="nt"&gt;-c&lt;/span&gt; path_to_your_file
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And after making changes to any conf file, you can apply it using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;nginx &lt;span class="nt"&gt;-s&lt;/span&gt; reload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you go on &lt;code&gt;http://localhost:8080&lt;/code&gt;, you'll see the html being served. 🎉 &lt;/p&gt;

&lt;h4&gt;
  
  
  Serving other static content
&lt;/h4&gt;

&lt;p&gt;If you try to add styles to your HTML content using a CSS file and serve it using the current configuration it will not work.&lt;/p&gt;

&lt;p&gt;To make this work, you have to set the correct mime types in the configuration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;...
http &lt;span class="o"&gt;{&lt;/span&gt;
  types &lt;span class="o"&gt;{&lt;/span&gt;
    text/css   css&lt;span class="p"&gt;;&lt;/span&gt;
    text/html  html&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="o"&gt;}&lt;/span&gt;

  server &lt;span class="o"&gt;{&lt;/span&gt;
    ...
  &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But manually adding these mime types for all different kinds of assets is cumbersome. Therefore, NGINX comes with a default &lt;code&gt;mime.types&lt;/code&gt; file that can be used here.&lt;/p&gt;

&lt;p&gt;After adding the default mime types file, our configuration looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c"&gt;# include mime.types; (if you did not create a custom file)&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen  8080&lt;span class="p"&gt;;&lt;/span&gt;
        root    /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After reloading the conf, our HTML and CSS should be working as expected but now we have support for a lot of types.&lt;/p&gt;

&lt;h4&gt;
  
  
  The &lt;code&gt;location&lt;/code&gt; block
&lt;/h4&gt;

&lt;p&gt;Let's assume you've the following directory structure:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqetn8rftijhco3cscfvx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqetn8rftijhco3cscfvx.png" alt="Directory structure" width="544" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Going to &lt;code&gt;/animals&lt;/code&gt;, will serve the &lt;code&gt;index.html&lt;/code&gt; file inside the &lt;code&gt;animals&lt;/code&gt; directory. What if you want to have another endpoint &lt;code&gt;/forest&lt;/code&gt; that serves the same file?&lt;/p&gt;

&lt;p&gt;We can use the &lt;code&gt;location&lt;/code&gt; block to specify the full path and then using &lt;code&gt;alias&lt;/code&gt; we can set the directory that will serve the files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen  8080&lt;span class="p"&gt;;&lt;/span&gt;
        root    /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;

        location /forest &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nb"&gt;alias&lt;/span&gt; /Users/syfe/Desktop/tutorials/nginx-test/html/animals&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the above configuration, requests to &lt;code&gt;/forest&lt;/code&gt; will be served from &lt;code&gt;animals&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;What if someone deletes the &lt;code&gt;animals&lt;/code&gt; directory or the file we're trying to serve is not available? We can provide fallback files using &lt;code&gt;try_files&lt;/code&gt; directive.&lt;/p&gt;

&lt;p&gt;Let's create a fallback file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsw0zhj62m0pu195pizpt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsw0zhj62m0pu195pizpt.png" alt="Directory structure" width="542" height="256"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let's update the configuration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen  8080&lt;span class="p"&gt;;&lt;/span&gt;
        root    /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;

        location /animals &lt;span class="o"&gt;{&lt;/span&gt;
            root /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;
            try_files /animals/fallback.html /index.html &lt;span class="o"&gt;=&lt;/span&gt;404&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when a user visits &lt;code&gt;/animals&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First the server will look for &lt;code&gt;/animals/index.html&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If it doesn't exist, it'll look for &lt;code&gt;/animals/fallback.html&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If our fallback file is missing it'll try to serve the &lt;code&gt;index.html&lt;/code&gt; at root.&lt;/li&gt;
&lt;li&gt;If it cannot find any file listed by us, it'll throw a 404 error.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Redirects
&lt;/h4&gt;

&lt;p&gt;It is quite easy to set up redirections using NGINX. Let's update the configuration to redirect all incoming traffic from &lt;code&gt;/birds&lt;/code&gt; to &lt;code&gt;/animals&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen  8080&lt;span class="p"&gt;;&lt;/span&gt;
        root    /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;

        location /animals &lt;span class="o"&gt;{&lt;/span&gt;
            root /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        location /birds &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return &lt;/span&gt;307 /animals&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Returning with &lt;code&gt;307&lt;/code&gt; does the trick.&lt;/p&gt;

&lt;h4&gt;
  
  
  Reverse Proxy
&lt;/h4&gt;

&lt;p&gt;To forward requests to another server we can use the &lt;code&gt;proxy_pass&lt;/code&gt; directive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen 8080&lt;span class="p"&gt;;&lt;/span&gt;

        location / &lt;span class="o"&gt;{&lt;/span&gt;
            proxy_pass http://192.168.10.5:8080&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, all the requests to &lt;code&gt;localhost:8080&lt;/code&gt; will be forwarded to &lt;code&gt;http://192.168.10.5:8080&lt;/code&gt;. This is helpful when you don't want to reveal the actual server or want to relay requests to different servers based on different paths.&lt;/p&gt;

&lt;h4&gt;
  
  
  Load Balancing
&lt;/h4&gt;

&lt;p&gt;Sometimes, in high traffic situations, we might spin up multiple instances to handle the load. NGINX can act as a load balancer and evenly distribute requests among all the instances.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1n38ba394njqdv9xbkv0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1n38ba394njqdv9xbkv0.png" alt="Load balancing" width="800" height="413"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This ensures a seamless experience for our users without any downtime.&lt;/p&gt;

&lt;p&gt;Let's update the configuration to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    upstream instances &lt;span class="o"&gt;{&lt;/span&gt;
        server 192.168.10.2:8080&lt;span class="p"&gt;;&lt;/span&gt;
        server 192.168.10.3:8080&lt;span class="p"&gt;;&lt;/span&gt;
        server 192.168.10.4:8080&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen 8080&lt;span class="p"&gt;;&lt;/span&gt;

        location / &lt;span class="o"&gt;{&lt;/span&gt;
            proxy_pass http://instances&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;upstream&lt;/code&gt; block is used to specify a group of servers that can be referenced by &lt;code&gt;proxy_pass&lt;/code&gt;. NGINX will automatically take care of distributing the requests evenly.&lt;/p&gt;

&lt;h4&gt;
  
  
  Logging
&lt;/h4&gt;

&lt;p&gt;With all that you've learnt so far, you'll be able to do a lot of cool things. One final(and important) thing that will help you in your journey is - Logging.&lt;/p&gt;

&lt;p&gt;Let's update the configuration to add access logs on our server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;events &lt;span class="o"&gt;{}&lt;/span&gt;

http &lt;span class="o"&gt;{&lt;/span&gt;
    include /opt/homebrew/etc/nginx/mime.types&lt;span class="p"&gt;;&lt;/span&gt;

    log_format main &lt;span class="s1"&gt;'$remote_addr - $remote_user [$time_local] "$request" '&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    access_log /Users/syfe/Desktop/tutorials/nginx-test/access.log main&lt;span class="p"&gt;;&lt;/span&gt;

    server &lt;span class="o"&gt;{&lt;/span&gt;
        listen 8080&lt;span class="p"&gt;;&lt;/span&gt;
        root /Users/syfe/Desktop/tutorials/nginx-test/html&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We provide the format using &lt;code&gt;log_format&lt;/code&gt; directive. The &lt;code&gt;access_log&lt;/code&gt; directive takes the path to store the logs and the format we specified earlier.&lt;/p&gt;




&lt;p&gt;That's it for this post! I hope this will get you started or at least now you understand what NGINX is. The &lt;a href="https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt; for NGINX is well written if you wish to explore further.&lt;/p&gt;

&lt;p&gt;🤝 I'd love to connect on &lt;a href="https://linkedin.com/in/thesanjeevsharma" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; or &lt;a href="https://x.com/thesnjvsharma" rel="noopener noreferrer"&gt;X&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://syfe.com/careers" rel="noopener noreferrer"&gt;Syfe&lt;/a&gt; is hiring devs. 👨‍💻🌏&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>nginx</category>
      <category>beginners</category>
      <category>devops</category>
    </item>
  </channel>
</rss>
