<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[KawalJain]]></title><description><![CDATA[KawalJain]]></description><link>https://blog.kawaljain.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 16 Apr 2026 14:36:25 GMT</lastBuildDate><atom:link href="https://blog.kawaljain.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[🚀 SOLID Principles Series – Part 2: Open/Closed Principle (OCP)]]></title><description><![CDATA[Open/Closed Principle (OCP)
Make your code ready for change — without breaking old stuff

“A class should be open for extension but closed for modification.”— Bertrand Meyer


What Does That Even Mean?
Let’s break it down:

Open for extension = You c...]]></description><link>https://blog.kawaljain.com/solid-principles-series-part-2-openclosed-principle-ocp</link><guid isPermaLink="true">https://blog.kawaljain.com/solid-principles-series-part-2-openclosed-principle-ocp</guid><category><![CDATA[#OpenClosedPrinciple]]></category><category><![CDATA[@Open/Closed Principle]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[solidjs]]></category><category><![CDATA[#ObjectOrientedProgramming]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Clean Code Tips]]></category><category><![CDATA[cleancode]]></category><category><![CDATA[Code Quality]]></category><category><![CDATA[anvikjs]]></category><category><![CDATA[kawaljain]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Fri, 23 May 2025 17:39:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748250087258/4908d5a2-b4da-4f72-8f60-26ef9ba7a651.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-openclosed-principle-ocp">Open/Closed Principle (OCP)</h1>
<h3 id="heading-make-your-code-ready-for-change-without-breaking-old-stuff">Make your code ready for change — without breaking old stuff</h3>
<blockquote>
<p>“A class should be open for extension but closed for modification.”<br />— <em>Bertrand Meyer</em></p>
</blockquote>
<hr />
<h2 id="heading-what-does-that-even-mean">What Does That Even Mean?</h2>
<p>Let’s break it down:</p>
<ul>
<li><p><strong>Open for extension</strong> = You can <strong>add new things</strong> to it (new features, types, logic).</p>
</li>
<li><p><strong>Closed for modification</strong> = You <strong>don’t change old working code</strong> that’s already been tested.</p>
</li>
</ul>
<p>So basically:</p>
<blockquote>
<p>You should be able to add new features <strong>without editing old code</strong>.</p>
</blockquote>
<hr />
<h2 id="heading-a-real-life-example">A Real-Life Example</h2>
<p>Imagine you built a school prize system:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPrize</span>(<span class="hljs-params">category</span>) </span>{
  <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'sports'</span>) <span class="hljs-keyword">return</span> <span class="hljs-string">'Trophy'</span>;
  <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'science'</span>) <span class="hljs-keyword">return</span> <span class="hljs-string">'Medal'</span>;
  <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'music'</span>) <span class="hljs-keyword">return</span> <span class="hljs-string">'Certificate'</span>;
}
</code></pre>
<p>Now you want to add "<strong>Art</strong>" as a new category.</p>
<h3 id="heading-what-do-you-have-to-do"><strong>What do you have to do?</strong></h3>
<p>You’ll go inside the <strong>getPrize()</strong> function and change it — but that might accidentally break the others!</p>
<hr />
<h2 id="heading-lets-follow-the-rule">Let’s Follow the Rule</h2>
<p>We’ll make a system in which each category has its own logic:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Prize</span> </span>{
  getPrize() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'No prize'</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SportsPrize</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Prize</span> </span>{
  getPrize() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Trophy'</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SciencePrize</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Prize</span> </span>{
  getPrize() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Medal'</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MusicPrize</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Prize</span> </span>{
  getPrize() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Certificate'</span>;
  }
}
</code></pre>
<p>Now to add <strong>Art</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ArtPrize</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Prize</span> </span>{
  getPrize() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Sketchbook'</span>;
  }
}
</code></pre>
<ul>
<li><p>No changes to old classes.</p>
</li>
<li><p>We just <strong>extended</strong> the system by adding a new class.</p>
</li>
</ul>
<blockquote>
<p>That’s the <strong>Open/Closed Principle</strong>!</p>
</blockquote>
<hr />
<h2 id="heading-why-should-you-care">Why Should You Care?</h2>
<ul>
<li><p>Adding new feature is easier</p>
</li>
<li><p>Easily maintainable when project will grow.</p>
</li>
<li><p>You don’t need to worry about the old code</p>
</li>
</ul>
<hr />
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>The Open/Closed Principle is like <strong>building with LEGO</strong>:</p>
<ul>
<li><p>You <strong>don’t</strong> break the <strong>old code</strong>.</p>
</li>
<li><p>You just <strong>add new code</strong>!</p>
</li>
</ul>
<p>The <strong>Liskov Substitution Principle</strong>—what happens when classes don't behave as we expect them to—will be covered in the upcoming post.</p>
<hr />
<h3 id="heading-lets-keep-building-together">Let’s Keep Building Together</h3>
<p>I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><strong><em>Thanks for reading</em></strong></p>
<p><strong><em>Happy coding!</em></strong></p>
<p><strong><em>If you enjoyed the article and would like to show your support, be sure to:</em></strong></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://kawaljain.medium.com/"><strong><em>Medium</em></strong></a></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://blog.kawaljain.com/"><strong><em>Hashnode</em></strong></a></p>
<p><strong><em>Checkout more</em></strong> <a target="_blank" href="http://kawaljain.com/"><strong><em>Portfolio</em></strong></a></p>
<p><strong><em>Checkout more</em></strong> <a target="_blank" href="https://project.kawaljain.com/">Work</a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[🚀 SOLID Principles Series – Part 1: Single Responsibility Principle (SRP)]]></title><description><![CDATA[There is no better way to start off my post than introducing you to the SOLID Principles – a set of five rules that every developer, regardless of experience, needs to master in order to produce clean, scalable, performance-oriented, and easy-to-main...]]></description><link>https://blog.kawaljain.com/solid-principles-series-part-1-single-responsibility-principle-srp</link><guid isPermaLink="true">https://blog.kawaljain.com/solid-principles-series-part-1-single-responsibility-principle-srp</guid><category><![CDATA[SolidJavascript]]></category><category><![CDATA[SOLID principles]]></category><category><![CDATA[#SOLIDPrinciples]]></category><category><![CDATA[anvikjs]]></category><category><![CDATA[kawaljain]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Design patterns in JavaScript]]></category><category><![CDATA[Clean Architecture]]></category><category><![CDATA[clean code]]></category><category><![CDATA[cleancode]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Tue, 20 May 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748016498990/82d20f77-1685-4728-9480-7baecc6850a6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There is no better way to start off my post than introducing you to the <strong>SOLID Principles</strong> – a set of <strong>five</strong> <strong>rules</strong> that every <strong>developer</strong>, regardless of experience, needs to master in order to produce <strong>clean, scalable, performance-oriented, and easy-to-maintain code</strong>. With this in mind, allow me to introduce to you the S of SOLID: The Single Responsibility Principle (SRP).</p>
<h2 id="heading-single-responsibility-principle-srp">Single Responsibility Principle (SRP)</h2>
<p>The <strong>Single Responsibility Principle</strong> states:</p>
<blockquote>
<p>“A class should have only one reason to change.” – <em>Robert C. Martin</em></p>
</blockquote>
<p>A class should only <strong>do one task</strong> and, ideally, have <strong>one responsibility.</strong> A class that consists of more than one responsibility has the potential to become coupled with multiple system aspects. This would mean that when a single responsibility changes, unexpected and unwanted bugs could arise.</p>
<hr />
<h2 id="heading-the-problem-with-multiple-responsibilities">The Problem with Multiple Responsibilities</h2>
<p>Imagine you're working with the <strong>User</strong> class in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, email) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.email = email;
  }

  validateEmail() {
    <span class="hljs-comment">// Validate email format</span>
  }

  saveToDatabase() {
    <span class="hljs-comment">// Logic to save user to DB</span>
  }

  sendWelcomeEmail() {
    <span class="hljs-comment">// Email logic</span>
  }
}
</code></pre>
<p>This User Class Handler does <strong>too much responsibilities</strong>:</p>
<ul>
<li><p>It Validates user data</p>
</li>
<li><p>It Handles persistence</p>
</li>
<li><p>It Sends emails</p>
</li>
</ul>
<p>Consider a scenario where you want to change the logic of email-sending — you have to change the User class which is unrelated to user data. This in itself violates SRP.</p>
<hr />
<h2 id="heading-refactoring-using-srp">Refactoring Using SRP</h2>
<p>Let’s break responsibilities into focused classes:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, email) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.email = email;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserValidator</span> </span>{
  <span class="hljs-keyword">static</span> validate(user) {
    <span class="hljs-comment">// Check if user.email is valid</span>
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRepository</span> </span>{
  <span class="hljs-keyword">static</span> save(user) {
    <span class="hljs-comment">// Save to DB</span>
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailService</span> </span>{
  <span class="hljs-keyword">static</span> sendWelcomeEmail(user) {
    <span class="hljs-comment">// Send email</span>
  }
}
</code></pre>
<p>Each class now has <strong>only one reason to change</strong>:</p>
<ul>
<li><p><code>UserValidator</code> changes only if validation logic changes.</p>
</li>
<li><p><code>UserRepository</code> changes only if storage changes.</p>
</li>
<li><p><code>EmailService</code> changes only if email logic changes.</p>
</li>
</ul>
<p>This is SRP in action!</p>
<hr />
<h2 id="heading-why-srp-matters">Why SRP Matters</h2>
<p>Maintaining a system SRP compliant is bound to improve:</p>
<ul>
<li><p>✅ <strong>Better Maintainability</strong> – Less change will improve unrelated broken functionality.</p>
</li>
<li><p>✅ <strong>Improved Readability</strong> – Focused and clear cut code will be far easier to read.</p>
</li>
<li><p>✅ <strong>Simpler Testing</strong> – Mocking and unit testing class is made easier by small class size.</p>
</li>
<li><p>✅ <strong>Enhanced Reusability</strong> – Independent use of each class without affecting the other improves reusability.</p>
</li>
</ul>
<hr />
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ul>
<li><p><strong>One class = One responsibility.</strong></p>
</li>
<li><p><strong>SRP</strong> makes your code <strong>cleaner</strong>, <strong>modular</strong>, and more <strong>testable</strong>.</p>
</li>
</ul>
<hr />
<h2 id="heading-whats-next">What’s Next?</h2>
<p>In the following sections of the series we will discuss the <strong>Open/Closed Principle</strong>, which teaches us how to design our code in a way that allows for easy extensibility but restricts alteration of existing code.</p>
<p>Follow along and stay tuned!</p>
<hr />
<p>I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><strong><em>Thanks for reading</em></strong></p>
<p><strong><em>Happy coding!</em></strong></p>
<p><strong><em>If you enjoyed the article and would like to show your support, be sure to:</em></strong></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://kawaljain.medium.com/"><strong><em>Medium</em></strong></a></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://blog.kawaljain.com/"><strong><em>Hashnode</em></strong></a></p>
<p><strong><em>Checkout more</em></strong> <a target="_blank" href="http://kawaljain.com/"><strong><em>Portfolio</em></strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Meet Your New Co-Workers: AI Agents]]></title><description><![CDATA[What Are AI Agents?

AI agents are smart software systems that can work independently.

They can plan, make decisions, and work with other agents without constant human guidance.

Examples include AutoGPT and BabyAGI.


Benefits

Flexibility: Agents ...]]></description><link>https://blog.kawaljain.com/meet-your-new-co-workers-ai-agents</link><guid isPermaLink="true">https://blog.kawaljain.com/meet-your-new-co-workers-ai-agents</guid><category><![CDATA[ai agents]]></category><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[System Design]]></category><category><![CDATA[technology]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[scalability]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Mon, 19 May 2025 17:30:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747675779470/7b0126f8-79e9-4703-adaf-46b1de5176a0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-are-ai-agents"><strong>What Are AI Agents?</strong></h2>
<ul>
<li><p>AI agents are smart software systems that can work independently.</p>
</li>
<li><p>They can plan, make decisions, and work with other agents without constant human guidance.</p>
</li>
<li><p>Examples include AutoGPT and BabyAGI.</p>
</li>
</ul>
<h2 id="heading-benefits"><strong>Benefits</strong></h2>
<ul>
<li><p><strong>Flexibility</strong>: Agents can handle specific tasks independently.</p>
</li>
<li><p><strong>Growth potential</strong>: Easy to add more agents as needed.</p>
</li>
<li><p><strong>Better decisions</strong>: Agents process information quickly.</p>
</li>
<li><p><strong>Cost savings</strong>: Automation reduces need for human staff.</p>
</li>
<li><p><strong>Independence</strong>: Agents can work without constant supervision.</p>
</li>
</ul>
<h2 id="heading-challenge-to-consider"><strong>Challenge To Consider</strong></h2>
<ul>
<li><p><strong>Over-automation risks:</strong> Not enough human supervision can cause errors.</p>
</li>
<li><p><strong>Context limitations</strong>: Agents will have problems dealing with complicated situations.</p>
</li>
<li><p><strong>Coordination difficulties:</strong> Controlling numerous agents cooperating is intricate</p>
</li>
<li><p><strong>Data security concerns:</strong> Require robust safeguards for personal data.</p>
</li>
<li><p><strong>Performance and cost issues:</strong> Agent systems are slow and costly to execute.</p>
</li>
</ul>
<h2 id="heading-system-design-reimagined"><strong>System Design Reimagined</strong></h2>
<ul>
<li><p>AI agents give rise to more adaptable, skill-based designs.</p>
</li>
<li><p>Old ideas such as resilience and observability require rethinking.</p>
</li>
<li><p>Trade-off between flexibility and predictability is very important.</p>
</li>
</ul>
<h2 id="heading-where-ai-agents-fits-and-where-it-may-fail"><strong>Where AI Agents fits and where it may fail</strong></h2>
<h3 id="heading-ai-agents-thrive-in-environments-with">AI agents thrive in environments with:</h3>
<ul>
<li><p>Well-defined domains and boundaries such as customer support &amp; content generation.</p>
</li>
<li><p>Fallback mechanisms available.</p>
</li>
<li><p>Chances of supervised learning.</p>
</li>
</ul>
<h3 id="heading-they-struggle-in-situations-with">They Struggle in situations with:</h3>
<ul>
<li><p>High-risk, irreversible choices such as patient monitoring in hospitals.</p>
</li>
<li><p>Intricate physical inspections.</p>
</li>
<li><p>Extremely volatile variables.</p>
</li>
<li><p>Legal or ethical responsibility demands.</p>
</li>
</ul>
<h2 id="heading-how-they-compare-to-microservices"><strong>How They Compare to Microservices</strong></h2>
<ul>
<li><p>Both break down complex systems into smaller parts.</p>
</li>
<li><p>Microservices follow fixed rules and use strict APIs.</p>
</li>
<li><p>AI agents can adapt and make decisions on their own.</p>
</li>
<li><p>Agents communicate using natural language instead of rigid protocols.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Rate Limiter]]></title><description><![CDATA[A Rate Limiter is a system that blocks a user request and only allows a certain number of requests to go through in a specified period.
Why Do we need it?

Prevent DDOS attacks and malicious users from overloading our site's traffic.

Preventing thes...]]></description><link>https://blog.kawaljain.com/rate-limiter</link><guid isPermaLink="true">https://blog.kawaljain.com/rate-limiter</guid><category><![CDATA[Sliding Window Log]]></category><category><![CDATA[rate-limiting]]></category><category><![CDATA[api security]]></category><category><![CDATA[Performance Optimization]]></category><category><![CDATA[scalability]]></category><category><![CDATA[DDoS Protection ]]></category><category><![CDATA[kawaljain]]></category><category><![CDATA[anvikjs]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Mon, 19 May 2025 06:30:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747653294117/a73292d5-2fbf-4817-85d1-3be16fd1b59b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A <strong><em>Rate Limiter</em></strong> is a system that blocks a user request and only allows a certain number of requests to go through in a specified period.</p>
<h2 id="heading-why-do-we-need-it"><strong>Why Do we need it?</strong></h2>
<ul>
<li><p><strong>Prevent DDOS attacks</strong> and malicious users from overloading our site's traffic.</p>
</li>
<li><p><strong>Preventing</strong> these attacks helps to <strong>reduce costs for the company</strong>. They need fewer servers to manage their traffic load.</p>
</li>
<li><p>To <strong>stop password guessing</strong> and <strong>brute-force</strong> assaults</p>
</li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>How will you <strong>identify</strong> the user?</p>
<ul>
<li><p>In an Authenticated system, we can use <strong>user ID</strong></p>
</li>
<li><p>In an Open API, it's common to use the <strong>IP address</strong>.</p>
</li>
</ul>
<h2 id="heading-rate-limiting-algorithms">Rate Limiting Algorithms</h2>
<p>There are multiple algorithms available for rate limiting. Choosing one depends on what you're optimizing for—<strong>accuracy</strong>, <strong>memory</strong>, <strong>burst</strong> <strong>handling</strong>, etc.</p>
<p>Let’s take a deeper look into one of the simplest and most accurate: the <strong>Sliding Window Log</strong>.</p>
<h2 id="heading-sliding-window-log"><strong>Sliding Window Log</strong></h2>
<hr />
<p>Sliding Window Log is a <strong>precise</strong> rate limiting <strong>algorithm</strong> that <strong>tracks</strong> each individual <strong>request’s timestamp</strong> and checks if a user has exceeded the <strong>allowed number of requests within a sliding time window</strong> (e.g., last 15 minutes).</p>
<h3 id="heading-lets-imagine"><strong>Let's Imagine</strong></h3>
<ul>
<li>Imagine a guard at a gate who keeps a notebook with the timestamps of when people entered.</li>
</ul>
<blockquote>
<p>The <strong>Rule</strong> is Only 100 people are allowed to enter within the 15 minutes.</p>
</blockquote>
<p>Each time some one arrived , the <strong>guards</strong></p>
<ul>
<li><p>Check the notebooks and <strong>remove</strong> all the <strong>entries</strong> older than 15 minutes</p>
</li>
<li><p><strong>Count</strong> the <strong>remaining</strong> entries</p>
</li>
<li><p>If <strong>less than 100</strong>, let the person in and record the current time.</p>
</li>
<li><p>If greater than 100 then reject the person</p>
</li>
</ul>
<h2 id="heading-how-it-works-in-code">How It Works in Code:</h2>
<hr />
<pre><code class="lang-javascript"><span class="hljs-comment">// In-memory store</span>
<span class="hljs-keyword">const</span> ipStore = {};

<span class="hljs-comment">// Middleware</span>
app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> ip = req.ip;
  <span class="hljs-keyword">const</span> now = <span class="hljs-built_in">Date</span>.now();

  <span class="hljs-keyword">if</span> (!ipStore[ip]) {
    ipStore[ip] = [];
  }

  <span class="hljs-comment">// Remove timestamps older than 15 minutes</span>
  ipStore[ip] = ipStore[ip].filter(<span class="hljs-function"><span class="hljs-params">timestamp</span> =&gt;</span> now - timestamp &lt; <span class="hljs-number">15</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span>);

  <span class="hljs-keyword">if</span> (ipStore[ip].length &gt;= <span class="hljs-number">100</span>) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">429</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Too many requests. Please try again later."</span> });
  }

  <span class="hljs-comment">// Add current request timestamp</span>
  ipStore[ip].push(now);
  next();
});
</code></pre>
<h2 id="heading-code-explanation">Code Explanation</h2>
<hr />
<h3 id="heading-create-an-in-memory-store"><strong>Create an in-memory store</strong></h3>
<ul>
<li>A JavaScript object (<strong>ipStore</strong>) is used to keep track of request timestamps for each IP address.</li>
</ul>
<h3 id="heading-capture-user-ip-and-current-time"><strong>Capture user IP and current time</strong></h3>
<ul>
<li>On each request, we get the user's IP (<strong>req.ip</strong>) and the current timestamp</li>
</ul>
<h3 id="heading-initialise-or-clean-request-log"><strong>Initialise or clean request log</strong></h3>
<ul>
<li><p>If it's the user's first request, we initialise an empty array.</p>
</li>
<li><p>We then filter out timestamps older than 15 minutes from their log.</p>
</li>
</ul>
<h3 id="heading-check-request-count"><strong>Check request count</strong></h3>
<ul>
<li>If the user has already made 100 requests in the last 15 minutes, respond with a <strong>429 Too Many Requests error</strong>.</li>
</ul>
<h3 id="heading-allow-and-log-the-request"><strong>Allow and log the request</strong></h3>
<ul>
<li>If under the limit, we store the current timestamp and let the request proceed using <strong>next()</strong>.</li>
</ul>
<hr />
<h2 id="heading-advantages"><strong>Advantages</strong></h2>
<ul>
<li><p>Very accurate</p>
</li>
<li><p>Always enforces <strong>X requests per sliding window</strong> exactly.</p>
</li>
</ul>
<h2 id="heading-disadvantages"><strong>Disadvantages</strong></h2>
<ul>
<li><p>Memory usage increases with traffic since every request is logged individually.</p>
</li>
<li><p>Needs cleanup or optimization in high-load systems.</p>
</li>
</ul>
<h2 id="heading-reference-links">Reference Links</h2>
<ul>
<li><p><a target="_blank" href="https://github.com/kawaljain/rate-limiter">Github Repo</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429">MDN Web Docs – HTTP 429 Too Many Requests</a></p>
</li>
<li><p><a target="_blank" href="https://expressjs.com/en/guide/using-middleware.html">Express.js Middleware Docs</a></p>
</li>
</ul>
<h2 id="heading-architecture-diagram">Architecture Diagram</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747572562250/8c21901e-64e0-4590-b64c-bbbc51282176.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We explored how a simple yet accurate rate limiter works using the Sliding Window Log algorithm. While it’s perfect for small apps and demos, it may need optimizations like Redis or token bucket for high-traffic production systems.</p>
<p>I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><strong><em>Thanks for reading</em></strong></p>
<p><strong><em>Happy coding!</em></strong></p>
<p><strong><em>If you enjoyed the article and would like to show your support, be sure to:</em></strong></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://kawaljain.medium.com/"><strong><em>Medium</em></strong></a></p>
<p><strong><em>Follow me On</em></strong> <a target="_blank" href="https://blog.kawaljain.com/"><strong><em>Hashnode</em></strong></a></p>
<p><strong><em>Checkout more</em></strong> <a target="_blank" href="http://kawaljain.com/"><strong><em>Portfolio</em></strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Building a Scalable Chat App]]></title><description><![CDATA[Real-time + Horizontal Scalability

Introduction
When I first started building this chat app, there was one requirement I had in mind: it has to be real-time, scalable, and easy to scale up. Sounds easy—until you introduce multiple servers to the mix...]]></description><link>https://blog.kawaljain.com/building-a-scalable-chat-app</link><guid isPermaLink="true">https://blog.kawaljain.com/building-a-scalable-chat-app</guid><category><![CDATA[Redis]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[System Design]]></category><category><![CDATA[scalability]]></category><category><![CDATA[websockets]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[chat application]]></category><category><![CDATA[messaging]]></category><category><![CDATA[messaging app]]></category><category><![CDATA[kawaljain]]></category><category><![CDATA[anvikjs]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Sun, 18 May 2025 01:40:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747653307478/fd791616-df3e-4353-8273-24d329dc4a40.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Real-time + Horizontal Scalability</p>
</blockquote>
<h2 id="heading-introduction">Introduction</h2>
<p>When I first started building this chat app, there was one requirement I had in mind: it has to be real-time, scalable, and easy to scale up. Sounds easy—until you introduce multiple servers to the mix.</p>
<p>In this article, I'm going to walk you through how I built a horizontally scalable chat app using:</p>
<ul>
<li><p>Socket.io for real-time messaging</p>
</li>
<li><p>Express.js as the backend framework</p>
</li>
<li><p>Redis Pub/Sub for synchronizing messages between servers</p>
</li>
</ul>
<p>This is a simple, yet strong—and horizontally scalable for production traffic capable—system.</p>
<h2 id="heading-architecture-overview">Architecture Overview</h2>
<p>Here’s a quick look at the architecture I implemented:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747532042485/d4ba6ee1-18ce-4146-b0ed-72fa3326a442.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Users 1–3 are connected to App Server A</p>
</li>
<li><p>User 4 is connected to App Server B</p>
</li>
<li><p>Both servers are connected to Redis</p>
</li>
<li><p>Redis handles message broadcasting between servers</p>
</li>
</ul>
<p>With this setup, the system is horizontally scalable—add app servers whenever needed.</p>
<h2 id="heading-why-redis-pubsub">Why Redis Pub/Sub?</h2>
<p>As your application grows, you can no longer rely on a single server. However, if there are lots of servers, broadcasting a chat message to everyone is tricky.</p>
<p>Here's why:</p>
<ul>
<li>Suppose User 1 is on Server A, and User 4 is on Server B. A message from one server will never reach the other user—unless servers talk to one another.</li>
</ul>
<p>That's when Redis Pub/Sub comes into play:</p>
<ul>
<li><p>Each app server subscribes to a Redis channel (e.g. chat)</p>
</li>
<li><p>When a message is posted, it's published to the channel</p>
</li>
<li><p>All servers receive it and emit to their connected clients</p>
</li>
</ul>
<blockquote>
<p>So Redis is essentially a router of messages between servers.</p>
</blockquote>
<h2 id="heading-test-scenario">Test Scenario</h2>
<p>Here’s what I tested:</p>
<ul>
<li><p>User 1 sends a message → hits Server A → published to Redis</p>
</li>
<li><p>Server B receives it via Redis → emits to User 4</p>
</li>
<li><p>Everyone sees the message in real-time</p>
</li>
</ul>
<blockquote>
<p>So even though users may be on different app servers, the chat is synchronized.</p>
</blockquote>
<h2 id="heading-why-this-architecture-works">Why This Architecture Works</h2>
<ul>
<li><p>Stateless app servers – easy to scale horizontally</p>
</li>
<li><p>Redis handles cross-server communication</p>
</li>
<li><p>No message loss or delay</p>
</li>
<li><p>Production-ready</p>
</li>
</ul>
<h2 id="heading-try-it-out">Try It Out</h2>
<ul>
<li><p><strong>Live Demo</strong>: <a target="_blank" href="https://app.eraser.io/workspace/LU14XzUDu6CVz3OMoxjG?origin=share&amp;elements=ciJZ2_jjHUNGqLR7eJfvxg">errasor.io</a></p>
</li>
<li><p><strong>Source Code</strong>: <a target="_blank" href="https://github.com/kawaljain/scalable_chat_app.git">GitHub Repo</a></p>
</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Redis Pub/Sub + Socket.IO is an excellent pairing to build highly scalable real-time systems. If you're working on anything from chat through multiplayer games or real-time dashboards—this pattern is worth learning.</p>
<p>I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><em>Thanks for reading</em></p>
<p><strong><em>Happy coding!</em></strong></p>
<p><em>If you enjoyed the article and would like to show your support, be sure to:</em></p>
<p><em>Follow me On</em> <a target="_blank" href="https://kawaljain.medium.com/"><strong><em>Medium</em></strong></a></p>
<p>Follow me On <a target="_blank" href="https://blog.kawaljain.com/"><strong>Hashnode</strong></a></p>
<p><em>Checkout more</em> <a target="_blank" href="http://kawaljain.com/"><strong><em>Portfolio</em></strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[How I Started My AI Journey as a Developer (Without Knowing What GPT Even Means)]]></title><description><![CDATA[As a full-stack developer, I spend hours every day writing code, fixing bugs, testing features, and managing tasks. Somewhere along the way, I realized I was repeating myself—writing similar functions, Googling the same snippets, and setting reminder...]]></description><link>https://blog.kawaljain.com/how-i-started-my-ai-journey-as-a-developer-without-knowing-what-gpt-even-means</link><guid isPermaLink="true">https://blog.kawaljain.com/how-i-started-my-ai-journey-as-a-developer-without-knowing-what-gpt-even-means</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[kawaljain]]></category><category><![CDATA[anvikjs]]></category><category><![CDATA[#DeveloperJourney]]></category><category><![CDATA[AI]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[openai]]></category><category><![CDATA[genai]]></category><category><![CDATA[BeginnerFriendly]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Sun, 20 Apr 2025 11:08:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747653423816/6c0701dc-254e-467d-93bc-159482f28174.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a full-stack developer, I spend hours every day writing code, fixing bugs, testing features, and managing tasks. Somewhere along the way, I realized I was repeating myself—writing similar functions, Googling the same snippets, and setting reminders for routine tasks.</p>
<h3 id="heading-but">But</h3>
<p>At the same time, I kept hearing things like:</p>
<blockquote>
<p><em>“AI will take developer jobs.”</em><br /><em>“If you don’t learn AI now, you’ll be irrelevant tomorrow.”</em><br /><em>“The future belongs to AI—developers who don’t adapt will be left behind.”</em></p>
</blockquote>
<hr />
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745147201783/80cd6d7c-bc9b-48f9-b1d9-53a4e870b153.gif" alt class="image--center mx-auto" /></p>
<p>Honestly, it was overwhelming. I wasn’t a data scientist. I am just a simple developer.</p>
<p>I don’t know what is <strong><em>models, LLMs, GenAI</em></strong>. But I knew how to <strong>build things.</strong> So I decided to stop overthinking and just start exploring.</p>
<h3 id="heading-where-i-actually-began-with-curiosity-not-theory">Where I Actually Began – With Curiosity, Not Theory</h3>
<p>I didn’t know where to start. With a lot of enthusiasm and curiosity, I just started. As any developer, I go to Google, YouTube, and ChatGPT to help me learn AI.</p>
<h3 id="heading-but-1">But</h3>
<p>It is not easy… there was so much information, tons of articles, but most of it was packed with heavy terms like transformer, tokenization, Ollama, Hugging Face, fine-tuning RAG, and so on.</p>
<p>My goal wasn’t to build the next ChatGPT; I just wanted to understand the basics. What exactly is GPT? What is OpenAI? Everyone kept saying "AI, AI, AI," but I needed to know the fundamentals first.</p>
<blockquote>
<p>That’s where my journey truly began.</p>
</blockquote>
<hr />
<h2 id="heading-understanding-the-basics">Understanding the Basics</h2>
<p>Once I started, I realized that to build anything useful, I first needed to understand some core concepts. It was shocking, but true—I finally got what <strong>tokenization</strong>, <strong>transformers</strong>, and <strong>self-attention</strong> actually mean.</p>
<blockquote>
<p>I used to thinkg ChatGPT and the OpenAI API would give the same answer to simple questions, like “What’s the weather in Delhi?”</p>
</blockquote>
<h2 id="heading-but-i-was-wrong">But I was wrong</h2>
<blockquote>
<p><strong>ChatGPT gave me the answer. But the OpenAI API said... nothing useful. Why?</strong></p>
</blockquote>
<h2 id="heading-here-is-the-simple-reason">Here is the simple reason</h2>
<p>🧠 <strong>ChatGPT</strong> is like a smart robot <strong>with internet and extra tools</strong>.<br />📦 <strong>OpenAI API</strong> is like the same smart robot, but <strong>without internet or tools</strong>.</p>
<p>In simple terms, <strong>ChatGPT is like a brain with a full working body</strong> — it can think <strong>and</strong> take action. It can search the web, do calculations, read files — just like a body helping the brain get things done.</p>
<p>But the <strong>OpenAI API is just the brain</strong>.<br />It’s super smart and can think really well, but it <strong>can’t do anything by itself</strong>.<br />If you want it to act — like search the web or get the weather — you have to <strong>build the body around it</strong>..</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>So that’s how my AI journey started with small steps, a curious mind, and a strong developer instinct.</p>
<p>From feeling overwhelmed by AI buzzwords to understanding how tools like ChatGPT actually work</p>
<blockquote>
<p>And trust me, if I can do it, <strong>you definitely can too.</strong></p>
</blockquote>
<p>In the next post, I’ll break down one of the most basic but powerful concepts in AI:</p>
<blockquote>
<p><strong>What is tokenization?</strong><br />(Hint: It’s like teaching a computer how to read!)</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[React Infinite Scroll Calendar]]></title><description><![CDATA[A Seamless Way to View Dates with Infinite Scrolling
Managing dates in your React applications just became a lot easier with the React Infinite Scroll Calendar. Whether you’re building a scheduling app, booking system, or simply need an efficient way...]]></description><link>https://blog.kawaljain.com/react-infinite-scroll-calendar</link><guid isPermaLink="true">https://blog.kawaljain.com/react-infinite-scroll-calendar</guid><category><![CDATA[kawaljain]]></category><category><![CDATA[anvikjs]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Wed, 20 Nov 2024 19:33:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745054935874/8af02cca-53f3-4983-93bf-bf39a58319eb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>A Seamless Way to View Dates with Infinite Scrolling</strong></p>
<p>Managing dates in your React applications just became a lot easier with the <a target="_blank" href="https://www.npmjs.com/package/@anvikjs/react-infinite-scroll-calendar"><strong><em>React Infinite Scroll Calendar</em></strong></a>. Whether you’re building a scheduling app, booking system, or simply need an efficient way to display calendar data, this package is here to help you implement an infinite scrolling calendar with minimal effort.</p>
<p>In this post, we’ll take a deep dive into the features, installation process, usage, and how you can contribute to the project to make it even better. Let’s get started!</p>
<h3 id="heading-what-is-react-infinite-scroll-calendar">🎉 What is React Infinite Scroll Calendar?</h3>
<p>The <a target="_blank" href="https://www.npmjs.com/package/@anvikjs/react-infinite-scroll-calendar"><strong><em>React Infinite Scroll Calendar</em></strong></a> is an open-source npm package that provides a smooth, infinite scrolling calendar component for React. This component allows you to display and navigate through months or days of the calendar dynamically without the need for page reloads or heavy data fetching, making it a great choice for performance-focused applications.</p>
<p>The key features of this calendar include:</p>
<ul>
<li><p><strong>Infinite Scrolling</strong>: Load and display months or days incrementally as the user scrolls.</p>
</li>
<li><p><strong>Customisable</strong>: Tailor the calendar’s appearance and behavior to fit your specific needs.</p>
</li>
<li><p><strong>Lightweight</strong>: Optimised for speed and responsiveness, with minimal dependencies.</p>
</li>
<li><p><strong>React Friendly</strong>: Fully compatible with React’s declarative style and hooks.</p>
</li>
</ul>
<p>Whether you’re building a project that requires displaying large amounts of calendar data or just need a more intuitive user experience, this package simplifies the process while ensuring excellent performance.</p>
<h3 id="heading-features"><strong>Features</strong></h3>
<p>Here are some of the key features that make the <a target="_blank" href="https://www.npmjs.com/package/@anvikjs/react-infinite-scroll-calendar"><strong><em>React Infinite Scroll Calendar</em></strong></a> stand out:</p>
<ul>
<li><p><strong>Infinite Scroll</strong>: Users can scroll through months or years without manually loading each one.</p>
</li>
<li><p><strong>Custom Event Handling</strong>: Easily add custom events and dates to specific days.</p>
</li>
<li><p><strong>Responsive Design</strong>: The calendar is fully responsive, adjusting smoothly for both desktop and mobile users.</p>
</li>
<li><p><strong>Customisable Styles</strong>: Apply your own CSS to tweak the look and feel of the calendar.</p>
</li>
<li><p><strong>Day Highlighting</strong>: Highlight specific days for events or important dates.</p>
</li>
</ul>
<h3 id="heading-installation">💻 Installation</h3>
<ol>
<li>Install the package</li>
</ol>
<p>npm install @anvikjs/react-infinite-scroll-calendar</p>
<p>2. Once installed, you can start using the calendar in your React components:</p>
<p>import InfiniteScrollCalendar from "@anvikjs/react-infinite-scroll-calendar";</p>
<p>3. Customising the Calendar</p>
<p>&lt;InfiniteScrollCalendar<br />calendarHeight={600}<br />calendarWidth={500}<br />renderMinDate={new Date(2022, 0, 1)}<br />renderMaxDate={new Date(2022, 11, 31)}<br />inifinityScroll={true}<br />isMultipleSelect={true}<br />selectedDates={["19-11-2024"]}<br />handleDateSelect={(date) =&gt; {<br />console.log(date);<br />}}<br />disabledDates={["18-11-2024"]}<br />/&gt;</p>
<h3 id="heading-how-to-contribute">🛠️ How to Contribute</h3>
<p>This package is <strong>open-source</strong>, and I welcome contributions from the community to make it even better. Whether you’re fixing bugs, adding features, or improving the documentation, there’s always something you can do. Whether you’re a seasoned developer or just getting started with React, there’s a place for you to contribute.</p>
<p>Here are some ways you can help:</p>
<ul>
<li><p><strong>⭐ Star the repo</strong>: If you find the project useful, give it a star on GitHub to show your support.</p>
</li>
<li><p><strong>🔧 Report bugs</strong>: If you find any bugs or issues, please report them on the Issues tab.</p>
</li>
<li><p><strong>💡 Suggest features</strong>: If you have ideas for improving the library, feel free to submit a feature request.</p>
</li>
<li><p><strong>📨 Submit a pull request</strong>: If you want to make changes or add features, open a pull request!</p>
</li>
</ul>
<h3 id="heading-documentation-and-resources"><strong>📚 Documentation and Resources</strong></h3>
<p>You can find detailed documentation on usage, configuration options, and examples in the <a target="_blank" href="https://github.com/anvikjs/react-infinite-scroll-calendar">GitHub repository</a> for the project.</p>
<p>If you have any issues or suggestions, feel free to open an issue on <a target="_blank" href="https://github.com/anvikjs/react-infinite-scroll-calendar/issues">GitHub</a> or ask questions via the issues page. I also encourage you to join the community and contribute to the ongoing development of this project!</p>
<h3 id="heading-acknowledgments">🤝 Acknowledgments</h3>
<p>A big thank you to everyone who has contributed to the development of this package! Your help has made this project possible.</p>
<h3 id="heading-conclusion">📝 Conclusion</h3>
<p>The <strong>React Infinite Scroll Calendar</strong> is a versatile and user-friendly component for anyone needing a scalable solution to display calendars in React apps.</p>
<p>With its infinite scrolling feature, ease of use, and customisation options, it’s the perfect tool to improve your application’s date display.</p>
<p>Feel free to explore the repository, contribute to its growth, and build awesome applications with it. Happy coding!</p>
<h3 id="heading-join-the-community">🌐 Join the Community</h3>
<p>This is just the beginning, and I’m excited to see where we can take <strong>react-infinite-scroll-calendar</strong> with the help of contributors like you!</p>
<ul>
<li><p><a target="_blank" href="https://github.com/anvikjs/react-infinite-scroll-calendar"><strong><em>GitHub</em></strong></a></p>
</li>
<li><p><a target="_blank" href="https://github.com/anvikjs/react-infinite-scroll-calendar/issues"><strong><em>Open Issues &amp; Discussions</em></strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/@anvikjs/react-infinite-scroll-calendar"><strong><em>NPM</em></strong></a></p>
</li>
</ul>
<h3 id="heading-connect-with-me">🌐 Connect with Me</h3>
<p>I’d love to hear your thoughts on this project, answer any questions, or simply connect with fellow developers! Feel free to reach out to me on any of the platforms below:</p>
<ul>
<li><p><strong>LinkedIn</strong>: <a target="_blank" href="https://www.linkedin.com/in/kawaljain/">Kawal Jain</a></p>
</li>
<li><p><strong>Portfolio</strong>: <a target="_blank" href="https://kawaljain.com/">kawaljain.com</a></p>
</li>
</ul>
<p>Whether you want to discuss the project, ask for help, or collaborate on open-source initiatives, don’t hesitate to reach out! Let’s stay connected and keep building amazing things together. 💬</p>
]]></content:encoded></item><item><title><![CDATA[Build Simple, Efficient, and Reusable Components for React NPM Packages]]></title><description><![CDATA[Objectives
I’ve always been a big fan for building code that is reusable, modular, and simple on its own but capable of achieving great things when combined with other components. The goal of this blog is to share how you can create reusable code mod...]]></description><link>https://blog.kawaljain.com/build-simple-efficient-and-reusable-components-for-react-npm-packages-ad40d5d86e75</link><guid isPermaLink="true">https://blog.kawaljain.com/build-simple-efficient-and-reusable-components-for-react-npm-packages-ad40d5d86e75</guid><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Tue, 19 Nov 2024 15:36:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745054955717/bb362c10-95eb-4c9d-b54a-8a47b5493125.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-objectives"><strong>Objectives</strong></h3>
<p>I’ve always been a big fan for building code that is reusable, modular, and simple on its own but capable of achieving great things when combined with other components. The goal of this blog is to share how you can create reusable code modules and publish them online so that developers around the world can access and use them in their own projects.</p>
<h3 id="heading-github">Github</h3>
<p>If you like to skip the end, here is the link: <a target="_blank" href="https://github.com/kawaljain/react-rollup-package-template"><strong><em>Repo</em></strong></a></p>
<p>In this <a target="_blank" href="https://github.com/kawaljain/react-rollup-package-template"><strong><em>repository</em></strong></a>, you’ll see how I’ve structured the code to keep it modular and focused on a single responsibility.</p>
<p>Feel free to check it out, experiment with it, and see how you might adapt or expand it for your own needs!</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Before starting, ensure you have:</p>
<ul>
<li>Node.js and NPM installed.</li>
<li>A basic understanding of React and package management.</li>
<li>Git configured (for publishing to NPM).</li>
<li>Rollup</li>
</ul>
<h3 id="heading-rollup">Rollup</h3>
<p><a target="_blank" href="https://rollupjs.org/">Rollup</a> is a powerful JavaScript bundler optimised for creating libraries. Its tree-shaking capabilities make it ideal for building NPM packages, especially React components. In this guide, we’ll walk through creating and publishing a React package using Rollup.</p>
<h3 id="heading-steps">Steps</h3>
<p><strong><em>Step 1: Setup the Project</em></strong></p>
<ol>
<li>Create a directory for your package:</li>
</ol>
<p>mkdir react-rollup-package-template<br />cd react-rollup-package-template</p>
<blockquote>
<p>Note: Make sure your npm package name is unique and there is no module with exactly the same as yours.</p>
</blockquote>
<p>2. Initialise the package:</p>
<p>npm init -y</p>
<p>This generates a <code>package.json</code> file.</p>
<p><strong><em>Step 2: Install Dependencies</em></strong></p>
<ol>
<li>Install React and ReactDOM as peer dependencies:</li>
</ol>
<p>npm install react react-dom --save-peer</p>
<p>2. Install Rollup and plugins:</p>
<p>npm install rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-babel rollup-plugin-peer-deps-external rollup-plugin-terser --save-dev</p>
<ol>
<li>[<strong>@rollup/plugin-node-resolve</strong>](http://twitter.com/rollup/plugin-node-resolve "Twitter profile for @rollup/plugin-node-resolve")<strong>:</strong> Resolves third-party modules in node_modules</li>
<li>[<strong>@rollup/plugin-commonjs</strong>](http://twitter.com/rollup/plugin-commonjs "Twitter profile for @rollup/plugin-commonjs")<strong>:</strong> Converts CommonJS modules to ES6 for Rollup to process.</li>
<li>[<strong>@rollup/plugin-babel</strong>](http://twitter.com/rollup/plugin-babel "Twitter profile for @rollup/plugin-babel")<strong>:</strong> Transpiles modern JavaScript.</li>
<li><strong>rollup-plugin-peer-deps-external:</strong> Automatically excludes peer dependencies like react.</li>
<li><strong>rollup-plugin-terser:</strong> Minifies the output.</li>
</ol>
<p><strong><em>Step 3: Write Your React Component</em></strong></p>
<p>Create a directory <strong>src/</strong> and add your component file.</p>
<p>// Dummy.tsx<br />import React from "react";<br />import "./style.css";  </p>
<p>import { DummyComponentProps } from "./Dummy.types";  </p>
<p>const DummyComponent: React.FC = ({ name, age }) =&gt; {<br />  return (<br />    <br />      <h1>I am {name}<br />      <h2>I am {age} years Old<br />    </h2></h1><br />  );<br />};  </p>
<p>export default DummyComponent;</p>
<p><strong><em>Step 4: Configure Rollup</em></strong></p>
<p>// rollup.config.js<br />import resolve from "@rollup/plugin-node-resolve";<br />import commonjs from "@rollup/plugin-commonjs";<br />import typescript from "@rollup/plugin-typescript";<br />import { terser } from "rollup-plugin-terser";<br />import external from "rollup-plugin-peer-deps-external";<br />import postcss from "rollup-plugin-postcss";<br />import dts from "rollup-plugin-dts";  </p>
<p>const packageJson = require("./package.json");  </p>
<p>export default [<br />  {<br />    input: "src/index.ts",<br />    output: [<br />      {<br />        file: packageJson.main,<br />        format: "cjs",<br />        sourcemap: true,<br />        name: "test-package-cr-typ",<br />      },<br />      {<br />        file: packageJson.module,<br />        format: "esm",<br />        sourcemap: true,<br />      },<br />    ],<br />    plugins: [<br />      external(),<br />      resolve(),<br />      commonjs(),<br />      typescript({<br />        tsconfig: "./tsconfig.json",<br />        tslib: { optional: false },<br />      }),<br />      postcss(),<br />      terser(),<br />    ],<br />  },<br />  {<br />    input: "dist/esm/index.d.ts",<br />    output: [{ file: "dist/index.d.ts", format: "esm" }],<br />    external: [/\.css$/],<br />    plugins: [dts.default()],<br />  },<br />];</p>
<p><strong><em>Step 5: Update package.json</em></strong></p>
<ol>
<li>Addd main and module fields to indicate the package entry points</li>
</ol>
<p>{<br />  "main": "dist/index.cjs.js",<br />  "module": "dist/index.esm.js"<br />}</p>
<p>2. Add a build script</p>
<p>{<br />  "scripts": {<br />    "build": "rollup -c --bundleConfigAsCjs"<br />  }<br />}</p>
<p>// package.json<br />{<br />  "name": "react-rollup-package-template",<br />  "version": "0.1.0",<br />  "type": "module",<br />  "main": "dist/cjs/index.js",<br />  "module": "dist/esm/index.js",<br />  "types": "dist/index.d.ts",<br />  "tslib": {<br />    "optional": true<br />  },<br />  "scripts": {<br />    "build": "rollup -c --bundleConfigAsCjs"<br />  },<br />  "devDependencies": {<br />    "@rollup/plugin-commonjs": "^28.0.1",<br />    "@rollup/plugin-node-resolve": "^15.3.0",<br />    "@rollup/plugin-typescript": "^8.5.0",<br />    "@types/react": "^18.3.12",<br />    "react": "^18.3.1",<br />    "rimraf": "^3.0.2",<br />    "rollup": "^4.27.2",<br />    "rollup-plugin-dts": "^6.1.1",<br />    "rollup-plugin-peer-deps-external": "^2.2.4",<br />    "rollup-plugin-postcss": "^4.0.2",<br />    "rollup-plugin-terser": "^7.0.2",<br />    "typescript": "^5.6.3"<br />  },<br />  "repository": {<br />    "type": "git",<br />    "url": "https://github.com/kawaljain/react-rollup-package-template.git"<br />  },<br />  "keywords": [<br />    "react",<br />    "reactjs",<br />    "react package",<br />    "create react package",<br />    "typescript react package",<br />    "create npm package",<br />    "create react npm package",<br />    "typescript create package",<br />    "package create",<br />    "example package npm create",<br />    "build npm package",<br />    "custom package react npm",<br />    "custom react typescript package"<br />  ],<br />  "author": "Kawal Jain",<br />  "license": "MIT",<br />  "bugs": {<br />    "url": "https://github.com/kawaljain/react-rollup-package-template/issues"<br />  },<br />  "homepage": "https://github.com/kawaljain/react-rollup-package-template#readme"<br />}</p>
<p><strong><em>Step 6: Build the Package</em></strong></p>
<p>Run the build command:</p>
<p>npm run build</p>
<p>This creates a <strong><em>dist/</em></strong> folder containing the compiled files.</p>
<p><strong><em>Step 7: Test the Package Locally</em></strong></p>
<ol>
<li>Link the package:</li>
</ol>
<p>npm run link</p>
<p>2. In a separate React project, link and test the package:</p>
<p>npm install react-rollup-package-template</p>
<p><strong><em>Step 8: Publish to NPM</em></strong></p>
<ol>
<li>Ensure you are logged into NPM</li>
</ol>
<p>npm login</p>
<p>2. Publish the package</p>
<p>npm publish</p>
<p>Use the <strong>access public</strong> flag if it's your first public package:</p>
<p>npm publish --access public</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Congratulations! You’ve created and published your first React package using Rollup. Share your package with the world, and remember to maintain it by updating dependencies and fixing issues.</p>
<h3 id="heading-tips">Tips</h3>
<ul>
<li>Add a <strong><em>README.MD</em></strong> with usage instructions.</li>
<li>Include a TypeScript declaration file <strong><em>(.d.ts)</em></strong> for TypeScript compatibility.</li>
<li>Keep peer dependencies updated for compatibility with the latest React versions</li>
</ul>
<p>That’s all from me, feel free to read and comment, If you find any issues, you can directly open an issue on GitHub. If you interest in flutter, you can read my article here in my medium. See you!</p>
<h3 id="heading-github-1">Github</h3>
<p>You can find the demo <strong>repository</strong>, which showcases some core principles of creating modular code. The goal is to demonstrate the building blocks that you can later expand into more complex, reusable components. While it’s not a complete library yet, this example can serve as a starting point for building larger, reusable components that can be shared across multiple projects.</p>
<p>Feel free to check it out, experiment with it, and see how you might adapt or expand it for your own needs!</p>
<blockquote>
<p><em>Thanks for reading</em></p>
<p><strong><em>Happy coding!</em></strong></p>
<p><em>If you enjoyed the article and would like to show your support, be sure to:</em></p>
<p><em>Follow me On</em> <a target="_blank" href="https://kawaljain.medium.com/"><strong><em>Medium</em></strong></a></p>
<p><em>Follow me On</em> <a target="_blank" href="https://dev.to/kawaljain"><strong><em>Dev</em></strong></a></p>
<p><em>Checkout more</em> <a target="_blank" href="http://kawaljain.com/"><strong><em>Portfolio</em></strong></a></p>
</blockquote>
<h3 id="heading-in-plain-english">In Plain English 🚀</h3>
<p><em>Thank you for being a part of the</em> <a target="_blank" href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a> <em>community! Before you go:</em></p>
<ul>
<li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li>
<li>Follow us: <a target="_blank" href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a target="_blank" href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a target="_blank" href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a target="_blank" href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a target="_blank" href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a target="_blank" href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li>
<li><a target="_blank" href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li>
<li>More content at <a target="_blank" href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Building My Own Markdown Parser: A Developer’s Journey 🚀]]></title><description><![CDATA[Hello Readers,
In this post, I’m going to explain what is Markdown, how Markdown works and why it’s so useful. We’ll dive into its key features, common uses, and show you how to get started with it.
Markdown has always been a go-to for developers whe...]]></description><link>https://blog.kawaljain.com/building-my-own-markdown-parser</link><guid isPermaLink="true">https://blog.kawaljain.com/building-my-own-markdown-parser</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Markdown, How to write markdown file, ]]></category><category><![CDATA[React]]></category><category><![CDATA[markdown]]></category><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Sun, 20 Oct 2024 07:37:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745054941522/02e96f0e-c26a-4129-8fa9-e4f239ea1a3e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Hello Readers,</strong></p>
<p>In this post, I’m going to explain what is Markdown, how Markdown works and why it’s so useful. We’ll dive into its key features, common uses, and show you how to get started with it.</p>
<p>Markdown has always been a go-to for developers when it comes to writing clean and readable documentation. But have you ever wondered how the text you write in markdown turns into beautifully formatted HTML? 🤔</p>
<blockquote>
<p><strong><em>Let’s explore!</em></strong></p>
</blockquote>
<h3 id="heading-what-is-markdown">What is Markdown ?</h3>
<p>A <strong>Markdown file</strong> (with a .md or .markdown extension) is a simple, lightweight format for writing structured text that can easily be converted into HTML or other formats.The core idea behind Markdown is to allow users to write text that is both easy to read in plain form and can be converted into HTML without complex code or tags.</p>
<h3 id="heading-key-features-of-markdown">Key Features of Markdown:</h3>
<p><strong>Plain Text-Based</strong>: Markdown files are readable in any text editor and don’t require special software to view.</p>
<p><strong>Lightweight Syntax</strong>: With simple symbols like #, *, and [](), you can create headings, lists, links, and more.</p>
<p><strong>Extensible</strong>: Many platforms and tools support custom extensions, so you can add tables, footnotes, or even code blocks.</p>
<h3 id="heading-common-use-case">Common Use Case</h3>
<ul>
<li><p><strong>Documentation</strong></p>
</li>
<li><p><strong>Content Creation</strong></p>
</li>
<li><p><strong>Note-Taking and Writing</strong></p>
</li>
<li><p><strong>Technical Communication</strong></p>
</li>
</ul>
<h3 id="heading-a-developers-journey"><strong>A Developer’s Journey 🚀</strong></h3>
<p>My journey with Markdown began when I used it to document my projects on <a target="_blank" href="https://github.com/kawaljain"><strong><em>GitHub</em></strong></a>. Its simplicity and versatility amazed me, sparking my curiosity about how such a markup language could be created from scratch.</p>
<p>I embarked on a fun and challenging journey — building my own Markdown parser from scratch! It was a deep dive into parsing and lexing, but also an excellent way to sharpen my understanding of text transformation and regular expressions.</p>
<h3 id="heading-key-challenges">Key Challenges:</h3>
<ul>
<li><p><strong>Handling Edge Cases:</strong> Markdown is simple, but edge cases like nested lists or inline HTML can make parsing tricky.</p>
</li>
<li><p><strong>Efficient Parsing:</strong> Ensuring the parser handles both small and large documents efficiently.</p>
</li>
<li><p><strong>Regex Mastery:</strong> Understanding and leveraging regular expressions to correctly interpret different markdown elements like headings, lists, links, and code blocks.</p>
</li>
</ul>
<h3 id="heading-project-step">Project Step</h3>
<p>Here are the steps to set up the project, which is developed in React.js. You can find an <a target="_blank" href="https://markdown.kawaljain.com/"><strong><em>online demo link</em></strong></a> for your reference. Additionally, be sure to check out the GitHub <a target="_blank" href="https://github.com/kawaljain/markdown-parser/blob/master/README.md"><strong><em>README</em></strong></a> file for detailed instructions and information.</p>
<p><strong>Clone this repository:</strong></p>
<p>git clone https://github.com/kawaljain/markdown-parser.git</p>
<p><strong>Navigate to the project directory:</strong></p>
<p>cd markdown-parser</p>
<p><strong>Install dependencies:</strong></p>
<p>npm run install</p>
<p>Now run the following commands assuming you are in markdown-parser directory or simply follow this <a target="_blank" href="https://github.com/kawaljain/markdown-parser/blob/master/README.md"><strong><em>documentation</em></strong></a>.</p>
<p>npm run dev</p>
<p>The app will run on your localhost. Simply <strong>Ctrl + Click</strong> the provided link to open it in your browser. And Congrats! You’ve successfully built your very own Markdown parser!</p>
<h3 id="heading-wrapping-up">Wrapping up</h3>
<p>This project has been a truly rewarding experience! It not only deepened my understanding of Markdown but also enhanced my skills in writing parsers and working with text processing overall. I look forward to applying what I’ve learned to future projects!</p>
<h3 id="heading-contributions-amp-feedback">Contributions &amp; Feedback**!**</h3>
<p>I’m excited to announce that I’m open-sourcing this project and would love for others to contribute or share feedback on how I can make it even better. Whether you’re passionate about markup languages, parsers, or just want to collaborate, your ideas and input are welcome! Stay tuned for the <a target="_blank" href="https://github.com/kawaljain/markdown-parser">repo link</a></p>
<p>let’s build something amazing together! 📂</p>
<h3 id="heading-reference-links">Reference Links</h3>
<p>Here are some helpful resources:</p>
<ul>
<li><p><a target="_blank" href="https://react.dev/">React Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://www.markdownguide.org/">Markdown Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://www.markdownguide.org/basic-syntax/">Basic Markdown Syntax Guid</a></p>
</li>
<li><p><a target="_blank" href="https://markdown.kawaljain.com/">Online Demo</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/kawaljain/markdown-parser">Github Repository</a></p>
</li>
</ul>
<h3 id="heading-mission-accomplished-unraveling-the-code">Mission Accomplished: Unraveling the Code!</h3>
<p>As I wrap up this journey of creating my own Markdown parser, I’m thrilled with the insights and skills I’ve gained along the way. This project has not only challenged me but has also deepened my appreciation for the beauty and simplicity of Markdown.</p>
<p>I encourage you to dive into the code, experiment with your own features, and share your ideas. Whether you’re a seasoned developer or just starting, there’s always something new to learn and explore. Thank you for joining me on this adventure — let’s keep pushing the boundaries of what we can create together!</p>
<blockquote>
<p>Thanks for reading</p>
<p><strong>Happy coding!</strong></p>
<p>If you enjoyed the article and would like to show your support, be sure to:</p>
<p>Follow me On <a target="_blank" href="https://kawaljain.medium.com/"><strong>Medium</strong></a></p>
<p>Follow me On <a target="_blank" href="https://dev.to/kawaljain"><strong>Dev</strong></a></p>
<p>Checkout more <a target="_blank" href="http://kawaljain.com"><strong>Portfolio</strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Javascript Interview Question Explanation -Asynchronous Behaviour]]></title><description><![CDATA[Introduction
In this article, we will explore a fascinating piece of JavaScript code that demonstrates the asynchronous nature of the language, particularly how closures and the setTimeout function work together. If you’ve ever been puzzled by why yo...]]></description><link>https://blog.kawaljain.com/javascript-interview-question-explanation-asynchronous-behaviour-2588082f7b61</link><guid isPermaLink="true">https://blog.kawaljain.com/javascript-interview-question-explanation-asynchronous-behaviour-2588082f7b61</guid><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Tue, 15 Oct 2024 13:00:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745054949000/0f1d3c8d-7db1-4a5a-9bf3-78e04a779a0c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<p>In this article, we will explore a fascinating piece of JavaScript code that demonstrates the asynchronous nature of the language, particularly how <strong><em>closures</em></strong> and the <strong><em>setTimeout</em></strong> function work together. If you’ve ever been puzzled by why your loop outputs unexpected results, you’re in the right place!</p>
<h3 id="heading-key-concept">Key Concept</h3>
<p><strong>Asynchronous Programming:</strong> JavaScript is single-threaded, meaning it can only execute one piece of code at a time. However, it can handle asynchronous operations, allowing certain tasks to run in the background while the main thread continues executing.</p>
<p><strong>SetTimeout</strong>: This function is used to execute a piece of code after a specified delay. It takes two parameters: a callback function and a delay in milliseconds.</p>
<p><strong>Closures</strong>: A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. This is crucial for understanding how variables are accessed in asynchronous callbacks.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }, i * <span class="hljs-number">1000</span>);
}
</code></pre>
<p>Before we dive into the details, take a moment to look at this code snippet. Try to guess what the output will be based on your current understanding. This approach not only helps reinforce your JavaScript skills but also makes the explanation that follows much more meaningful</p>
<blockquote>
<p>Think about how JavaScript will process each line. Once you’ve made your guess, keep reading to see if you got it right!</p>
</blockquote>
<h3 id="heading-explanation">Explanation</h3>
<p>Let break down the code step by step:</p>
<p><strong>Loop Execution:</strong> The loop runs five times, incrementing <strong>`i`</strong> from 0 to 4.</p>
<p><strong>setTimeout:</strong> For each value of <strong>`i`</strong>, a <strong>`setTimeout`</strong> is scheduled to log <strong>`i`</strong> after <strong>`i * 1000`</strong> milliseconds.</p>
<p><strong>Closures:</strong> By the time the <strong>`setTimeout`</strong> callbacks execute, the loop has already completed, and <strong>`i`</strong> has a final value of 5. Therefore, all the callbacks will log <strong>`5`.</strong></p>
<h3 id="heading-what-you-might-except">What you might except</h3>
<pre><code class="lang-javascript"><span class="hljs-number">0</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
</code></pre>
<h3 id="heading-what-actually-happen">What actually Happen</h3>
<pre><code class="lang-javascript"><span class="hljs-number">5</span>
<span class="hljs-number">5</span>
<span class="hljs-number">5</span>
<span class="hljs-number">5</span>
<span class="hljs-number">5</span>
</code></pre>
<p>However, this is not the actual output that you would see. The reason for this is a common JavaScript behavior related to the scope of the <strong>`i`</strong> variable.</p>
<p>In the provided code, the <strong>`i`</strong> variable is declared using <strong>`var`</strong>, which means it has function scope. When the <strong>`setTimeout()`</strong> functions are executed, the loop has already completed, and the value of <strong>`i`</strong> is 5. Therefore, all the <strong>`setTimeout()`</strong> functions will log the value 5 to the console, regardless of the delay.</p>
<h3 id="heading-fixing-the-issue">Fixing the Issue</h3>
<p>To achieve the expected output of `0, 1, 2, 3, 4`,</p>
<p>We can use an **`Immediately Invoked Function Expression (IIFE) `**to create a new scope for each iteration.<br />We can use <strong>`let`</strong> keyword instead of <strong>`var`</strong>.</p>
<h3 id="heading-solution">Solution</h3>
<h3 id="heading-1-immediately-invoked-function-expression-iife"><strong>1- Immediately Invoked Function Expression (IIFE)</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
  (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">i</span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(i);
    }, i * <span class="hljs-number">1000</span>);
  })(i);
}
</code></pre>
<p>Now, each <strong>`setTimeout`</strong> will captures the current value of <strong>`i`</strong>, and output will be:</p>
<pre><code class="lang-javascript"><span class="hljs-number">0</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
</code></pre>
<h3 id="heading-2-by-using-let-keyword">2- By Using `Let` keyword</h3>
<p>The <strong>`let`</strong> keyword creates a block-scoped variable, which means that each iteration of the loop will have its own copy of the <strong>`i`</strong> variable, and the <strong>`setTimeout()`</strong> functions will capture the correct value of <strong>`i`</strong> for each iteration.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Understanding how JavaScript handles asynchronous operations and closures is crucial for writing effective code. The original code snippet serves as a great example of how the <strong>`setTimeout`</strong> function interacts with the loop variable <strong>`i`</strong>. By using an <strong>`IIFE`</strong>, we can ensure that each timeout logs the correct value. So, the next time you encounter a similar situation, remember the power of closures and how they can help you manage asynchronous behaviour in JavaScript</p>
<h3 id="heading-mission-accomplished-unraveling-the-code">Mission Accomplished: Unraveling the Code!</h3>
<p>I hope this explanation not only clarified the code but also sparked some curiosity to explore further. JavaScript is full of surprises and powerful tools, and each piece you learn brings you closer to mastering it.</p>
<blockquote>
<p>Thanks for reading</p>
</blockquote>
<p>I hope you enjoyed this breakdown! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><strong>Happy coding!</strong></p>
<p>If you enjoyed the article and would like to show your support, be sure to:</p>
<p>Follow me On <a target="_blank" href="https://kawaljain.medium.com/"><strong>Medium</strong></a></p>
<p>Follow me On <a target="_blank" href="https://dev.to/kawaljain"><strong>Dev</strong></a></p>
<p>Checkout more <a target="_blank" href="http://kawaljain.com"><strong>Portfolio</strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Javascript Interview Question Explanation- Object Properties]]></title><description><![CDATA[Hello Reader,
I am going to explain javascript interview coding question. How javascript compiler works and what it actually produces as output.
I’ll break down each part of the output, explain why it appears this way, and connect it back to the spec...]]></description><link>https://blog.kawaljain.com/javascript-interview-question-explanation-object-properties</link><guid isPermaLink="true">https://blog.kawaljain.com/javascript-interview-question-explanation-object-properties</guid><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Mon, 07 Oct 2024 20:45:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747820514458/641d3bcb-e327-4334-80a9-f210f92a686d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Reader,</p>
<p>I am going to explain javascript interview coding question. How javascript compiler works and what it actually produces as output.</p>
<p>I’ll break down each part of the output, explain why it appears this way, and connect it back to the specific lines of code responsible</p>
<p>let a = {};<br />let b = { key: 'b' };<br />let c = { key: 'c' };</p>
<p>a[b] = 123;<br />a[c] = 456;</p>
<p>console.log(a[b]);</p>
<p>Before we dive into the details, take a moment to look at this code snippet. Try to guess what the output will be based on your current understanding. This approach not only helps reinforce your JavaScript skills but also makes the explanation that follows much more meaningful</p>
<p>“Think about how JavaScript will process each line. Once you’ve made your guess, keep reading to see if you got it right!”</p>
<h3 id="heading-explanation-of-above-code">Explanation of above code</h3>
<ol>
<li>For Line-1</li>
</ol>
<p>let a = {};</p>
<p>Above code, creates an empty object, and assign to the variable <strong>‘a’.</strong></p>
<p>2. For Line-2</p>
<p>let b = { key: 'b' };</p>
<p>This line creates an object with a single property key and the value ‘b’, and assigns it to the variable ‘b’.</p>
<p>3. For Line-3</p>
<p>let c = { key: 'c' };</p>
<p>This line creates an object with a single propery key and the value ‘c’, and assign it to the variable ‘c’.</p>
<p>4 For line-4</p>
<p>a[b] = 123;</p>
<p><code>**a[b] = 123**</code> This line sets a property of the object <strong>a</strong> using the object <strong>b</strong> as the key. In JavaScript, when an object is used as a key in another object, the object is first converted to a string using the <strong>toString()</strong> method. In this case, the string representation of the object <strong>b</strong> is <strong>“[object Object]”</strong> . So, the property <strong>“[object Object]”</strong> of the object <strong>a</strong> is set to the value <strong>123.</strong></p>
<p>5. For Line-5</p>
<p>a[c] = 456;</p>
<p>Similar to the Previous step, “c” is also a object and converted to string, it becomes <strong>“</strong> <strong>“[object Object]””.</strong></p>
<p>Therefore, the line a[c] = 456; is equivalent to <strong>“a[object Object]”=456</strong>, which means that object has <strong>“[object Object]”</strong> property and its value is <strong>456</strong>.</p>
<p>6. For Line-6</p>
<p>console.log(a[b])</p>
<p>Output is <strong>456.</strong> when you try to access the the property “<strong>a[b]”</strong>, javascript again convert b to string, which is <strong>“[object Object]”</strong>. Since object has a property with the key <strong>“[object Object]”</strong> and its value is 456. So it will print the output.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In Summary, the code demonstrate that when an object is used as a key in the another object, the object is first converted to a string representation, which is <strong>“[object Object]”</strong> by default. This means that the objects b and c are treated as the same key, and the last value assigned to that key is the one that is retrieved.</p>
<h3 id="heading-mission-accomplished-unraveling-the-code">Mission Accomplished: Unraveling the Code!</h3>
<p>I hope this explanation not only clarified the code but also sparked some curiosity to explore further. JavaScript is full of surprises and powerful tools, and each piece you learn brings you closer to mastering it.</p>
<p>Thanks for reading, and I hope you enjoyed this breakdown! Feel free to share your thoughts, questions, or ideas for future topics in the comments.</p>
<blockquote>
<p><strong><em>Happy coding!</em></strong></p>
<p><em>If you enjoyed the article and would like to show your support, be sure to:</em></p>
<p>Follow me On <a target="_blank" href="https://kawaljain.medium.com/"><strong>Medium</strong></a></p>
<p>Follow me On <a target="_blank" href="https://dev.to/kawaljain"><strong>Dev</strong></a></p>
<p>Checkout more <a target="_blank" href="http://kawaljain.com"><strong>Portfolio</strong></a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[JavaScript Singleton Design Patterns]]></title><description><![CDATA[What is SingleTon Pattern?
The Singleton Pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it.This single instance is unmodifiable.
It can be accessed globally throughout the application
T...]]></description><link>https://blog.kawaljain.com/javascript-singleton-design-patterns-8b11c75a3b8e</link><guid isPermaLink="true">https://blog.kawaljain.com/javascript-singleton-design-patterns-8b11c75a3b8e</guid><dc:creator><![CDATA[Kawal Jain]]></dc:creator><pubDate>Mon, 07 Oct 2024 19:25:13 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-what-is-singleton-pattern"><strong><em>What is SingleTon Pattern?</em></strong></h3>
<p>The Singleton Pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it.<br />This single instance is unmodifiable.</p>
<p>It can be accessed globally throughout the application</p>
<p>This singleton can be shared globally across multiple files within the application. The imports of this Singleton all reference the same instance</p>
<p><code>class Singleton {   constructor() {   this.data = [];   }</code></p>
<p><code>addData(item) {   this.data.push(item);   }</code></p>
<p><code>getData() {   return this.data;   }   }</code></p>
<p><code>const instance = new Singleton();   Object.freeze(instance); // Prevent modification</code></p>
<p><code>export default instance;</code></p>
<p>Now, If you import Singleton file into multiple files, you always get the same instance.</p>
<h3 id="heading-where-to-use"><strong>Where to use:</strong></h3>
<p>When you have objects that need to coordinate actions across an application, like a database connection pool</p>
<p>When you want to maintain a single configuration object that’s accessible across different modules.</p>
<p>When you need a global logging service that any part of the application can access.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Singleton Pattern is powerful, but it should be used judiciously, as it creates global state and can make testing challenging. When used in the right context, however, it can help you organize and simplify the structure of your application.</p>
<blockquote>
<p>If you enjoyed the article and would like to show your support, be sure to:</p>
<p>Checkout more <a target="_blank" href="http://kawaljain.com"><strong>Portfolio</strong></a></p>
</blockquote>
]]></content:encoded></item></channel></rss>