<?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[Developers-catalog]]></title><description><![CDATA[Developers-catalog]]></description><link>https://blogs.abhishekdogra.in</link><generator>RSS for Node</generator><lastBuildDate>Sat, 23 May 2026 12:19:09 GMT</lastBuildDate><atom:link href="https://blogs.abhishekdogra.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Understanding the this Keyword in JavaScript]]></title><description><![CDATA[One of the most confusing concepts for JavaScript beginners is:
this

At first, it may seem mysterious because its value changes in different situations.
But the core idea is actually simple.
In most ]]></description><link>https://blogs.abhishekdogra.in/understanding-the-this-keyword-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/understanding-the-this-keyword-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 13:13:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/c3c7c69a-2c9c-4dfe-ab28-f4e22ddd849a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most confusing concepts for JavaScript beginners is:</p>
<pre><code class="language-id=&quot;this001&quot;">this
</code></pre>
<p>At first, it may seem mysterious because its value changes in different situations.</p>
<p>But the core idea is actually simple.</p>
<p>In most cases:</p>
<pre><code class="language-id=&quot;this002&quot;">this refers to the object that is calling the function
</code></pre>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What <code>this</code> represents</p>
</li>
<li><p><code>this</code> in global context</p>
</li>
<li><p><code>this</code> inside objects</p>
</li>
<li><p><code>this</code> inside functions</p>
</li>
<li><p>How calling context changes <code>this</code></p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>What Does <code>this</code> Mean?</h1>
<p>The value of:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>depends on:</p>
<pre><code class="language-id=&quot;this004&quot;">How a function is called
</code></pre>
<p>Not where it is written.</p>
<p>This is the most important thing to remember.</p>
<hr />
<h1>Real-Life Analogy</h1>
<p>Imagine a TV remote.</p>
<p>The same remote can control:</p>
<ul>
<li><p>TV</p>
</li>
<li><p>AC</p>
</li>
<li><p>projector</p>
</li>
</ul>
<p>depending on which device it is connected to.</p>
<p>Similarly:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>changes depending on the caller.</p>
<hr />
<h1><code>this</code> in Global Context</h1>
<p>In the browser global scope:</p>
<pre><code class="language-javascript">console.log(this);
</code></pre>
<p>usually refers to:</p>
<pre><code class="language-id=&quot;this007&quot;">window object
</code></pre>
<p>because the browser’s global object is:</p>
<pre><code class="language-javascript">window
</code></pre>
<hr />
<h1>Simple Visualization</h1>
<pre><code class="language-id=&quot;this009&quot;">Global Scope
     ↓
this → window
</code></pre>
<hr />
<h1><code>this</code> Inside Objects</h1>
<p>Inside an object method:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>refers to the object calling the method.</p>
<hr />
<h1>Example</h1>
<pre><code class="language-javascript">const person = {
  name: "Rahul",

  greet() {
    console.log(this.name);
  }
};

person.greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;this012&quot;">Rahul
</code></pre>
<hr />
<h1>Why Does It Work?</h1>
<p>Because:</p>
<pre><code class="language-javascript">person
</code></pre>
<p>is calling:</p>
<pre><code class="language-javascript">greet()
</code></pre>
<p>So:</p>
<pre><code class="language-javascript">this → person
</code></pre>
<hr />
<h1>Caller → Function Relationship</h1>
<pre><code class="language-id=&quot;this016&quot;">person object
      ↓
calls greet()
      ↓
this refers to person
</code></pre>
<hr />
<h1>Another Example</h1>
<pre><code class="language-javascript">const car = {
  brand: "BMW",

  showBrand() {
    console.log(this.brand);
  }
};

car.showBrand();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;this018&quot;">BMW
</code></pre>
<p>Again:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>points to:</p>
<pre><code class="language-javascript">car
</code></pre>
<hr />
<h1><code>this</code> Inside Normal Functions</h1>
<p>Inside regular standalone functions:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>behaves differently.</p>
<hr />
<h1>Example</h1>
<pre><code class="language-javascript">function show() {
  console.log(this);
}

show();
</code></pre>
<p>In browsers, this usually refers to:</p>
<pre><code class="language-id=&quot;this023&quot;">window object
</code></pre>
<hr />
<h1>Why Beginners Get Confused</h1>
<p>Many beginners think:</p>
<pre><code class="language-id=&quot;this024&quot;">this always refers to the current object
</code></pre>
<p>But that is not true.</p>
<p>Its value depends on:</p>
<pre><code class="language-id=&quot;this025&quot;">The calling context
</code></pre>
<hr />
<h1>Calling Context Changes <code>this</code></h1>
<p>This is the most important rule.</p>
<hr />
<h1>Example 1</h1>
<pre><code class="language-javascript">const user = {
  name: "Aman",

  print() {
    console.log(this.name);
  }
};

user.print();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;this027&quot;">Aman
</code></pre>
<hr />
<h1>Example 2</h1>
<pre><code class="language-javascript">const obj = {
  name: "Rahul"
};

function show() {
  console.log(this.name);
}

obj.display = show;

obj.display();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;this029&quot;">Rahul
</code></pre>
<hr />
<h1>Why?</h1>
<p>Because now:</p>
<pre><code class="language-javascript">obj
</code></pre>
<p>is calling the function.</p>
<p>So:</p>
<pre><code class="language-javascript">this → obj
</code></pre>
<hr />
<h1>Different Contexts of <code>this</code></h1>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Value of <code>this</code></th>
</tr>
</thead>
<tbody><tr>
<td>Global scope (browser)</td>
<td>window</td>
</tr>
<tr>
<td>Object method</td>
<td>Calling object</td>
</tr>
<tr>
<td>Regular function</td>
<td>window/global object</td>
</tr>
<tr>
<td>Function called by object</td>
<td>That object</td>
</tr>
</tbody></table>
<hr />
<h1>Important Concept</h1>
<p>Remember:</p>
<pre><code class="language-id=&quot;this032&quot;">this is decided during function call, not function creation
</code></pre>
<p>This is a core JavaScript concept.</p>
<hr />
<h1>Common Beginner Mistakes</h1>
<h2>Confusing Variable Scope with <code>this</code></h2>
<p>Variables and:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>are different concepts.</p>
<hr />
<h2>Thinking <code>this</code> Is Fixed</h2>
<p>It changes based on:</p>
<pre><code class="language-id=&quot;this034&quot;">Who calls the function
</code></pre>
<hr />
<h2>Forgetting Object Caller</h2>
<p>Example:</p>
<pre><code class="language-javascript">person.greet()
</code></pre>
<p>Here:</p>
<pre><code class="language-javascript">person
</code></pre>
<p>is the caller.</p>
<hr />
<h1>Real-World Example</h1>
<p>Imagine a banking app.</p>
<p>Example:</p>
<pre><code class="language-javascript">const account = {
  balance: 5000,

  showBalance() {
    console.log(this.balance);
  }
};
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;this038&quot;">5000
</code></pre>
<p>The method accesses the current object’s data using:</p>
<pre><code class="language-javascript">this
</code></pre>
<hr />
<h1>Why <code>this</code> Is Useful</h1>
<p><code>this</code> helps objects:</p>
<p>✅ Access their own properties ✅ Create reusable methods ✅ Work dynamically ✅ Support object-oriented programming</p>
<hr />
<h1>Visual Summary</h1>
<pre><code class="language-id=&quot;this040&quot;">Caller
   ↓
Function Executes
   ↓
this points to caller
</code></pre>
<hr />
<h1>Practice Assignment</h1>
<p>Try these exercises yourself.</p>
<hr />
<h1>1. Create an Object</h1>
<p>Add:</p>
<ul>
<li><p>name</p>
</li>
<li><p>age</p>
</li>
<li><p>method using <code>this</code></p>
</li>
</ul>
<hr />
<h1>2. Print Object Properties</h1>
<p>Use:</p>
<pre><code class="language-javascript">this.name
</code></pre>
<p>inside method.</p>
<hr />
<h1>3. Create Multiple Objects</h1>
<p>Observe how:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>changes.</p>
<hr />
<h1>4. Try Standalone Function</h1>
<p>Create a normal function and log:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>Observe output.</p>
<hr />
<h1>Final Thoughts</h1>
<p>The:</p>
<pre><code class="language-javascript">this
</code></pre>
<p>keyword is one of the most important JavaScript concepts.</p>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;this045&quot;">this usually refers to whoever is calling the function.
</code></pre>
<p>Understanding <code>this</code> is essential for:</p>
<ul>
<li><p>objects</p>
</li>
<li><p>methods</p>
</li>
<li><p>classes</p>
</li>
<li><p>event handling</p>
</li>
<li><p>advanced JavaScript concepts</p>
</li>
</ul>
<p>As you continue learning JavaScript, mastering <code>this</code> will help you understand how JavaScript functions and objects truly work internally.</p>
<hr />
<p>And now, you know how the <code>this</code> keyword works in JavaScript.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[The Node.js Event Loop Explained]]></title><description><![CDATA[One of the most important concepts behind Node.js performance is:
The Event Loop

The event loop is the reason Node.js can handle many requests efficiently even though JavaScript runs on:
A single thr]]></description><link>https://blogs.abhishekdogra.in/the-node-js-event-loop-explained</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/the-node-js-event-loop-explained</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 13:10:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/aee35780-4c5c-4c5c-b47b-bff6e48d1983.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most important concepts behind Node.js performance is:</p>
<pre><code class="language-id=&quot;loop001&quot;">The Event Loop
</code></pre>
<p>The event loop is the reason Node.js can handle many requests efficiently even though JavaScript runs on:</p>
<pre><code class="language-id=&quot;loop002&quot;">A single thread
</code></pre>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What the event loop is</p>
</li>
<li><p>Why Node.js needs an event loop</p>
</li>
<li><p>Task queue vs call stack</p>
</li>
<li><p>How async operations are handled</p>
</li>
<li><p>Timers vs I/O callbacks</p>
</li>
<li><p>Role of event loop in scalability</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>Why Node.js Needs an Event Loop</h1>
<p>JavaScript in Node.js runs on:</p>
<pre><code class="language-id=&quot;loop003&quot;">A single main thread
</code></pre>
<p>A single thread can execute:</p>
<pre><code class="language-id=&quot;loop004&quot;">Only one task at a time
</code></pre>
<p>So the question becomes:</p>
<pre><code class="language-id=&quot;loop005&quot;">How does Node.js handle thousands of requests efficiently?
</code></pre>
<p>The answer is:</p>
<pre><code class="language-id=&quot;loop006&quot;">The Event Loop
</code></pre>
<hr />
<h1>Real-Life Analogy</h1>
<p>Imagine a restaurant manager.</p>
<p>The manager:</p>
<ul>
<li><p>accepts customer orders</p>
</li>
<li><p>sends cooking tasks to kitchen staff</p>
</li>
<li><p>continues taking new orders</p>
</li>
<li><p>serves completed orders later</p>
</li>
</ul>
<p>The manager does not cook everything personally.</p>
<p>Similarly, the event loop manages tasks efficiently instead of waiting for every operation to finish.</p>
<hr />
<h1>What Is the Event Loop?</h1>
<p>The event loop is:</p>
<pre><code class="language-id=&quot;loop007&quot;">A task manager that continuously checks and executes pending tasks
</code></pre>
<p>It helps Node.js handle asynchronous operations efficiently.</p>
<hr />
<h1>Core Components</h1>
<p>To understand the event loop, we first need to understand:</p>
<ul>
<li><p>Call Stack</p>
</li>
<li><p>Task Queue</p>
</li>
<li><p>Async APIs</p>
</li>
</ul>
<hr />
<h1>What Is the Call Stack?</h1>
<p>The call stack stores functions currently being executed.</p>
<p>JavaScript executes code:</p>
<pre><code class="language-id=&quot;loop008&quot;">One function at a time
</code></pre>
<hr />
<h1>Simple Call Stack Example</h1>
<pre><code class="language-javascript">function first() {
  console.log("First");
}

function second() {
  console.log("Second");
}

first();
second();
</code></pre>
<p>Execution order:</p>
<pre><code class="language-id=&quot;loop010&quot;">first()
   ↓
second()
</code></pre>
<p>The call stack handles this sequential execution.</p>
<hr />
<h1>What Is the Task Queue?</h1>
<p>The task queue stores:</p>
<pre><code class="language-id=&quot;loop011&quot;">Completed asynchronous callbacks waiting to execute
</code></pre>
<p>Examples include:</p>
<ul>
<li><p>timers</p>
</li>
<li><p>file read callbacks</p>
</li>
<li><p>API responses</p>
</li>
</ul>
<hr />
<h1>Event Loop Core Idea</h1>
<p>The event loop continuously checks:</p>
<pre><code class="language-id=&quot;loop012&quot;">Is the call stack empty?
</code></pre>
<p>If yes:</p>
<pre><code class="language-id=&quot;loop013&quot;">Move callback from queue to stack
</code></pre>
<hr />
<h1>Event Loop Visualization</h1>
<pre><code class="language-id=&quot;loop014&quot;">Call Stack
     ↑
Event Loop
     ↑
Task Queue
</code></pre>
<p>The event loop acts as the bridge.</p>
<hr />
<h1>How Async Operations Work</h1>
<p>Async operations do not directly run inside the main JavaScript thread.</p>
<p>Instead:</p>
<pre><code class="language-id=&quot;loop015&quot;">Node.js delegates them to background system workers
</code></pre>
<hr />
<h1>Example Using setTimeout</h1>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
  console.log("Timer Done");
}, 2000);

console.log("End");
</code></pre>
<hr />
<h1>Understanding the Flow</h1>
<p>Step-by-step:</p>
<hr />
<h2>Step 1</h2>
<pre><code class="language-javascript">console.log("Start");
</code></pre>
<p>runs immediately.</p>
<p>Output:</p>
<pre><code class="language-id=&quot;loop018&quot;">Start
</code></pre>
<hr />
<h2>Step 2</h2>
<pre><code class="language-javascript">setTimeout()
</code></pre>
<p>is registered.</p>
<p>The timer runs in the background.</p>
<hr />
<h2>Step 3</h2>
<p>Execution continues immediately.</p>
<pre><code class="language-javascript">console.log("End");
</code></pre>
<p>runs.</p>
<p>Output:</p>
<pre><code class="language-id=&quot;loop021&quot;">End
</code></pre>
<hr />
<h2>Step 4</h2>
<p>After 2 seconds:</p>
<pre><code class="language-id=&quot;loop022&quot;">Timer callback enters task queue
</code></pre>
<hr />
<h2>Step 5</h2>
<p>When the call stack becomes empty:</p>
<pre><code class="language-id=&quot;loop023&quot;">Event loop pushes callback into stack
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;loop024&quot;">Timer Done
</code></pre>
<hr />
<h1>Final Output</h1>
<pre><code class="language-id=&quot;loop025&quot;">Start
End
Timer Done
</code></pre>
<p>This surprises many beginners initially.</p>
<hr />
<h1>Event Loop Execution Cycle Visualization</h1>
<pre><code class="language-id=&quot;loop026&quot;">Code Executes
      ↓
Async Task Registered
      ↓
Task Runs in Background
      ↓
Callback Added to Queue
      ↓
Event Loop Checks Stack
      ↓
Callback Executes
</code></pre>
<hr />
<h1>Timers vs I/O Callbacks</h1>
<p>Node.js handles different async operations similarly.</p>
<p>Examples:</p>
<ul>
<li><p>timers</p>
</li>
<li><p>file reads</p>
</li>
<li><p>database queries</p>
</li>
<li><p>API requests</p>
</li>
</ul>
<hr />
<h1>Timer Example</h1>
<pre><code class="language-javascript">setTimeout(() =&gt; {
  console.log("Hello");
}, 1000);
</code></pre>
<p>Timer callback enters queue after delay finishes.</p>
<hr />
<h1>File Read Example</h1>
<pre><code class="language-javascript">const fs = require("fs");

fs.readFile("test.txt", "utf-8", (err, data) =&gt; {
  console.log(data);
});
</code></pre>
<p>File reading happens asynchronously.</p>
<p>The callback executes later when file reading finishes.</p>
<hr />
<h1>Why the Event Loop Is Important</h1>
<p>Without the event loop:</p>
<pre><code class="language-id=&quot;loop029&quot;">Node.js would block while waiting for tasks
</code></pre>
<p>This would make servers slow and inefficient.</p>
<hr />
<h1>How Event Loop Helps Scalability</h1>
<p>The event loop allows Node.js to:</p>
<p>✅ Handle many requests ✅ Avoid blocking operations ✅ Keep servers responsive ✅ Process async tasks efficiently</p>
<p>This is one of the biggest reasons Node.js scales well.</p>
<hr />
<h1>Request Handling Flow in Node.js</h1>
<pre><code class="language-id=&quot;loop030&quot;">Incoming Request
        ↓
Node.js Registers Async Task
        ↓
Background Worker Handles Task
        ↓
Event Loop Waits
        ↓
Callback Executes
        ↓
Response Sent
</code></pre>
<hr />
<h1>Single Thread Does Not Mean Slow</h1>
<p>Many beginners think:</p>
<pre><code class="language-id=&quot;loop031&quot;">Single thread = bad performance
</code></pre>
<p>But Node.js becomes efficient because:</p>
<pre><code class="language-id=&quot;loop032&quot;">The event loop avoids waiting
</code></pre>
<hr />
<h1>Queue Analogy</h1>
<p>Imagine a customer support desk.</p>
<p>Requests are added to a queue.</p>
<p>The manager continuously checks:</p>
<pre><code class="language-id=&quot;loop033&quot;">Who is ready next?
</code></pre>
<p>The event loop behaves similarly.</p>
<hr />
<h1>Common Beginner Misconceptions</h1>
<h2>setTimeout Runs Exactly on Time</h2>
<p>Not always.</p>
<p>The callback runs only when:</p>
<pre><code class="language-id=&quot;loop034&quot;">Call stack becomes available
</code></pre>
<hr />
<h2>Async Tasks Execute Immediately</h2>
<p>Async tasks complete later and wait in queue until the stack is free.</p>
<hr />
<h2>Event Loop Executes Everything Simultaneously</h2>
<p>No.</p>
<p>JavaScript still executes one task at a time on the main thread.</p>
<hr />
<h1>Blocking vs Non-Blocking Reminder</h1>
<p>The event loop is the reason Node.js supports:</p>
<pre><code class="language-id=&quot;loop035&quot;">Non-blocking execution
</code></pre>
<p>Instead of waiting, Node.js continues processing other tasks.</p>
<hr />
<h1>Real-World Example</h1>
<p>Imagine a chat application.</p>
<p>Thousands of users may:</p>
<ul>
<li><p>send messages</p>
</li>
<li><p>receive notifications</p>
</li>
<li><p>connect simultaneously</p>
</li>
</ul>
<p>The event loop helps Node.js handle all these operations efficiently.</p>
<hr />
<h1>Practice Assignment</h1>
<p>Try these exercises yourself.</p>
<hr />
<h1>1. Experiment with setTimeout</h1>
<p>Observe execution order.</p>
<hr />
<h1>2. Use Multiple Timers</h1>
<p>Example:</p>
<pre><code class="language-javascript">setTimeout(() =&gt; {
  console.log("A");
}, 1000);

setTimeout(() =&gt; {
  console.log("B");
}, 0);
</code></pre>
<p>Predict output order.</p>
<hr />
<h1>3. Try File Reading</h1>
<p>Use:</p>
<pre><code class="language-javascript">fs.readFile()
</code></pre>
<p>and observe asynchronous behavior.</p>
<hr />
<h1>4. Understand Queue Behavior</h1>
<p>Think about how callbacks wait before execution.</p>
<hr />
<h1>Final Thoughts</h1>
<p>The event loop is one of the most important concepts in Node.js.</p>
<p>It allows Node.js to efficiently handle asynchronous operations using:</p>
<ul>
<li><p>call stack</p>
</li>
<li><p>task queue</p>
</li>
<li><p>background workers</p>
</li>
<li><p>callback execution</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;loop038&quot;">The event loop continuously moves completed async callbacks into execution when the call stack is free.
</code></pre>
<p>Understanding the event loop is essential for:</p>
<ul>
<li><p>backend development</p>
</li>
<li><p>API handling</p>
</li>
<li><p>performance optimization</p>
</li>
<li><p>scalable system design</p>
</li>
</ul>
<p>As you continue learning Node.js, this concept will appear everywhere in asynchronous programming.</p>
<hr />
<p>And now, you know how the Node.js event loop works.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Blocking vs Non-Blocking Code in Node.js]]></title><description><![CDATA[One of the biggest reasons Node.js became popular is its ability to handle many requests efficiently.
This happens because Node.js heavily relies on:
Non-blocking code

To understand Node.js properly,]]></description><link>https://blogs.abhishekdogra.in/blocking-vs-non-blocking-code-in-node-js</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/blocking-vs-non-blocking-code-in-node-js</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 13:08:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/b20004fd-016d-480c-b298-bcc1b74ebcea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the biggest reasons Node.js became popular is its ability to handle many requests efficiently.</p>
<p>This happens because Node.js heavily relies on:</p>
<pre><code class="language-id=&quot;block001&quot;">Non-blocking code
</code></pre>
<p>To understand Node.js properly, you must understand the difference between:</p>
<ul>
<li><p>blocking code</p>
</li>
<li><p>non-blocking code</p>
</li>
</ul>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What blocking code means</p>
</li>
<li><p>What non-blocking code means</p>
</li>
<li><p>Why blocking slows servers</p>
</li>
<li><p>Async operations in Node.js</p>
</li>
<li><p>Real-world examples like file reading and database calls</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>What Does “Blocking” Mean?</h1>
<p>Blocking means:</p>
<pre><code class="language-id=&quot;block002&quot;">The program must wait before moving to the next task
</code></pre>
<p>Execution stops until the current task finishes.</p>
<hr />
<h1>Simple Real-Life Analogy</h1>
<p>Imagine ordering food at a restaurant.</p>
<hr />
<h2>Blocking Behavior</h2>
<p>The waiter:</p>
<ul>
<li><p>takes one order</p>
</li>
<li><p>waits for food to finish</p>
</li>
<li><p>then takes the next order</p>
</li>
</ul>
<p>Other customers must wait.</p>
<hr />
<h2>Non-Blocking Behavior</h2>
<p>The waiter:</p>
<ul>
<li><p>takes one order</p>
</li>
<li><p>sends it to kitchen</p>
</li>
<li><p>immediately handles next customer</p>
</li>
</ul>
<p>This is much more efficient.</p>
<p>Node.js follows this second approach.</p>
<hr />
<h1>Understanding Blocking Code</h1>
<p>Blocking code prevents other operations from executing until completion.</p>
<hr />
<h1>Blocking Execution Timeline</h1>
<pre><code class="language-id=&quot;block003&quot;">Task 1 Running
      ↓
Wait Until Complete
      ↓
Task 2 Starts
      ↓
Task 3 Starts
</code></pre>
<p>Everything waits in sequence.</p>
<hr />
<h1>Blocking File Read Example</h1>
<p>Node.js provides synchronous methods that block execution.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

const data = fs.readFileSync("test.txt", "utf-8");

console.log(data);

console.log("Finished");
</code></pre>
<hr />
<h1>What Happens Here?</h1>
<p>Flow:</p>
<pre><code class="language-id=&quot;block005&quot;">Read File
    ↓
Wait Until File Fully Loaded
    ↓
Print Data
    ↓
Continue Execution
</code></pre>
<p>The server cannot continue until file reading completes.</p>
<hr />
<h1>Why Blocking Is Bad for Servers</h1>
<p>Imagine thousands of users accessing a server.</p>
<p>If one request blocks the server:</p>
<pre><code class="language-id=&quot;block006&quot;">Other requests must wait
</code></pre>
<p>This reduces:</p>
<ul>
<li><p>performance</p>
</li>
<li><p>scalability</p>
</li>
<li><p>responsiveness</p>
</li>
</ul>
<hr />
<h1>What Is Non-Blocking Code?</h1>
<p>Non-blocking code allows the program to:</p>
<pre><code class="language-id=&quot;block007&quot;">Continue executing while tasks run in background
</code></pre>
<p>Node.js heavily uses this model.</p>
<hr />
<h1>Non-Blocking Execution Timeline</h1>
<pre><code class="language-id=&quot;block008&quot;">Task 1 Starts
Task 2 Starts
Task 3 Starts
      ↓
Results Return Later
</code></pre>
<p>Execution keeps moving.</p>
<hr />
<h1>Non-Blocking File Read Example</h1>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

fs.readFile("test.txt", "utf-8", (err, data) =&gt; {
  console.log(data);
});

console.log("Finished");
</code></pre>
<hr />
<h1>Understanding the Execution Flow</h1>
<p>Flow:</p>
<pre><code class="language-id=&quot;block010&quot;">Start File Read
       ↓
Continue Execution
       ↓
Print "Finished"
       ↓
File Data Returns Later
</code></pre>
<p>Node.js does not wait for the file operation to complete.</p>
<hr />
<h1>Output Order</h1>
<p>Output may look like:</p>
<pre><code class="language-id=&quot;block011&quot;">Finished
File Content Here
</code></pre>
<p>because file reading happens asynchronously.</p>
<hr />
<h1>Why Node.js Uses Non-Blocking I/O</h1>
<p>I/O means:</p>
<pre><code class="language-id=&quot;block012&quot;">Input / Output Operations
</code></pre>
<p>Examples:</p>
<ul>
<li><p>file reading</p>
</li>
<li><p>database queries</p>
</li>
<li><p>API requests</p>
</li>
<li><p>network communication</p>
</li>
</ul>
<p>These operations take time.</p>
<p>Node.js avoids waiting unnecessarily.</p>
<hr />
<h1>Async Operations in Node.js</h1>
<p>Node.js delegates slow tasks to:</p>
<pre><code class="language-id=&quot;block013&quot;">Background system workers
</code></pre>
<p>while the main thread continues handling requests.</p>
<hr />
<h1>Event Loop Role</h1>
<p>The event loop checks for completed operations and executes callbacks when tasks finish.</p>
<hr />
<h1>Event Loop Flow</h1>
<pre><code class="language-id=&quot;block014&quot;">Request Arrives
       ↓
Async Task Delegated
       ↓
Node.js Handles Other Requests
       ↓
Task Completes
       ↓
Callback Executes
</code></pre>
<p>This is the core of Node.js scalability.</p>
<hr />
<h1>Real-World Example: Database Calls</h1>
<p>Database queries are usually slow compared to normal code execution.</p>
<hr />
<h2>Blocking Database Flow</h2>
<pre><code class="language-id=&quot;block015&quot;">Query Database
      ↓
Wait
      ↓
Continue
</code></pre>
<p>Server becomes idle while waiting.</p>
<hr />
<h2>Non-Blocking Database Flow</h2>
<pre><code class="language-id=&quot;block016&quot;">Send Query
     ↓
Handle Other Requests
     ↓
Database Responds Later
</code></pre>
<p>Much more efficient.</p>
<hr />
<h1>Why Non-Blocking Improves Performance</h1>
<p>Non-blocking systems can:</p>
<p>✅ Handle more users ✅ Process more requests ✅ Improve responsiveness ✅ Avoid server idle time</p>
<p>This is why Node.js works very well for:</p>
<ul>
<li><p>APIs</p>
</li>
<li><p>chat applications</p>
</li>
<li><p>streaming systems</p>
</li>
<li><p>real-time applications</p>
</li>
</ul>
<hr />
<h1>Blocking vs Non-Blocking Comparison</h1>
<table>
<thead>
<tr>
<th>Blocking</th>
<th>Non-Blocking</th>
</tr>
</thead>
<tbody><tr>
<td>Waits for task completion</td>
<td>Continues execution</td>
</tr>
<tr>
<td>Slower for many requests</td>
<td>Better scalability</td>
</tr>
<tr>
<td>Sequential execution</td>
<td>Async execution</td>
</tr>
<tr>
<td>Can freeze server</td>
<td>Keeps server responsive</td>
</tr>
</tbody></table>
<hr />
<h1>Synchronous vs Asynchronous</h1>
<p>Blocking often relates to:</p>
<pre><code class="language-id=&quot;block017&quot;">Synchronous execution
</code></pre>
<p>Non-blocking usually relates to:</p>
<pre><code class="language-id=&quot;block018&quot;">Asynchronous execution
</code></pre>
<p>Though they are closely related, they are not always identical concepts.</p>
<hr />
<h1>Common Async Operations in Node.js</h1>
<p>Examples include:</p>
<ul>
<li><p>file handling</p>
</li>
<li><p>database queries</p>
</li>
<li><p>API calls</p>
</li>
<li><p>timers</p>
</li>
<li><p>authentication requests</p>
</li>
</ul>
<p>Most backend systems rely heavily on async behavior.</p>
<hr />
<h1>Real-World Scenario</h1>
<p>Imagine a social media application.</p>
<p>Thousands of users may:</p>
<ul>
<li><p>upload posts</p>
</li>
<li><p>fetch notifications</p>
</li>
<li><p>load feeds</p>
</li>
</ul>
<p>If the server blocked for every request:</p>
<pre><code class="language-id=&quot;block019&quot;">Performance would collapse
</code></pre>
<p>Non-blocking architecture helps Node.js scale efficiently.</p>
<hr />
<h1>Common Beginner Misconceptions</h1>
<h2>Non-Blocking Means Multiple Threads</h2>
<p>Not exactly.</p>
<p>Node.js primarily uses:</p>
<pre><code class="language-id=&quot;block020&quot;">A single JavaScript thread
</code></pre>
<p>with asynchronous task delegation.</p>
<hr />
<h2>Async Code Runs Instantly</h2>
<p>Async tasks still take time.</p>
<p>Node.js simply avoids waiting during that time.</p>
<hr />
<h2>Blocking Is Always Bad</h2>
<p>Blocking code can still be useful for:</p>
<ul>
<li><p>small scripts</p>
</li>
<li><p>startup configuration</p>
</li>
<li><p>quick utilities</p>
</li>
</ul>
<p>But not ideal for high-traffic servers.</p>
<hr />
<h1>Practice Assignment</h1>
<p>Try these exercises yourself.</p>
<hr />
<h1>1. Use <code>readFileSync()</code></h1>
<p>Observe blocking behavior.</p>
<hr />
<h1>2. Use <code>readFile()</code></h1>
<p>Observe asynchronous behavior.</p>
<hr />
<h1>3. Compare Output Order</h1>
<p>Experiment with:</p>
<pre><code class="language-javascript">console.log()
</code></pre>
<p>before and after async operations.</p>
<hr />
<h1>4. Add <code>setTimeout()</code></h1>
<p>Observe how Node.js handles delayed execution.</p>
<p>Example:</p>
<pre><code class="language-javascript">setTimeout(() =&gt; {
  console.log("Done");
}, 2000);
</code></pre>
<hr />
<h1>5. Think About Real APIs</h1>
<p>Consider why asynchronous behavior matters for:</p>
<ul>
<li><p>authentication</p>
</li>
<li><p>database access</p>
</li>
<li><p>external APIs</p>
</li>
</ul>
<hr />
<h1>Final Thoughts</h1>
<p>Understanding blocking vs non-blocking code is essential for backend development with Node.js.</p>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;block023&quot;">Blocking code waits.
Non-blocking code continues execution.
</code></pre>
<p>Node.js became powerful because it efficiently handles asynchronous operations using:</p>
<ul>
<li><p>non-blocking I/O</p>
</li>
<li><p>event-driven architecture</p>
</li>
<li><p>the event loop</p>
</li>
</ul>
<p>This allows Node.js applications to remain:</p>
<ul>
<li><p>responsive</p>
</li>
<li><p>scalable</p>
</li>
<li><p>fast under heavy traffic</p>
</li>
</ul>
<p>As you continue learning backend engineering, mastering asynchronous thinking will become one of your most important skills.</p>
<hr />
<p>And now, you know the difference between blocking and non-blocking code in Node.js.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[REST API Design Made Simple with Express.js]]></title><description><![CDATA[REST API Design Made Simple with Express.js
Modern web applications constantly communicate between:

frontend and backend

mobile apps and servers

services and databases


This communication usually ]]></description><link>https://blogs.abhishekdogra.in/rest-api-design-made-simple-with-express-js</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/rest-api-design-made-simple-with-express-js</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 13:05:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/948a08e8-6b0f-4c0b-9764-3a518781b164.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>REST API Design Made Simple with Express.js</h1>
<p>Modern web applications constantly communicate between:</p>
<ul>
<li><p>frontend and backend</p>
</li>
<li><p>mobile apps and servers</p>
</li>
<li><p>services and databases</p>
</li>
</ul>
<p>This communication usually happens through:</p>
<pre><code class="language-id=&quot;rest001&quot;">REST APIs
</code></pre>
<p>REST APIs are one of the most important concepts in backend development.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What REST API means</p>
</li>
<li><p>Resources in REST architecture</p>
</li>
<li><p>HTTP methods</p>
</li>
<li><p>Status codes basics</p>
</li>
<li><p>Designing routes using REST principles</p>
</li>
<li><p>Building a simple users resource example</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>What Is an API?</h1>
<p>API stands for:</p>
<pre><code class="language-id=&quot;rest002&quot;">Application Programming Interface
</code></pre>
<p>An API allows different applications to communicate with each other.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;rest003&quot;">Frontend ↔ Backend
</code></pre>
<p>The frontend sends requests and the backend sends responses.</p>
<hr />
<h1>What Does REST Mean?</h1>
<p>REST stands for:</p>
<pre><code class="language-id=&quot;rest004&quot;">Representational State Transfer
</code></pre>
<p>It is a design style for building APIs.</p>
<p>REST APIs organize data around:</p>
<pre><code class="language-id=&quot;rest005&quot;">Resources
</code></pre>
<hr />
<h1>What Is a Resource in REST?</h1>
<p>A resource is simply:</p>
<pre><code class="language-id=&quot;rest006&quot;">A piece of data
</code></pre>
<p>Examples:</p>
<ul>
<li><p>users</p>
</li>
<li><p>products</p>
</li>
<li><p>orders</p>
</li>
<li><p>posts</p>
</li>
</ul>
<p>In REST APIs, each resource gets its own routes.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;rest007&quot;">/users
/products
/orders
</code></pre>
<hr />
<h1>Real-World Analogy</h1>
<p>Imagine a restaurant.</p>
<ul>
<li><p>You place an order → Request</p>
</li>
<li><p>Kitchen processes it → Server Logic</p>
</li>
<li><p>Food arrives → Response</p>
</li>
</ul>
<p>REST APIs work similarly.</p>
<pre><code class="language-id=&quot;rest008&quot;">Client Request
      ↓
Server Processes
      ↓
Response Returned
</code></pre>
<hr />
<h1>Understanding HTTP Methods</h1>
<p>REST APIs use HTTP methods to define actions.</p>
<p>The four most common methods are:</p>
<ul>
<li><p>GET</p>
</li>
<li><p>POST</p>
</li>
<li><p>PUT</p>
</li>
<li><p>DELETE</p>
</li>
</ul>
<p>These map directly to CRUD operations.</p>
<hr />
<h1>CRUD vs HTTP Methods</h1>
<table>
<thead>
<tr>
<th>CRUD Operation</th>
<th>HTTP Method</th>
</tr>
</thead>
<tbody><tr>
<td>Create</td>
<td>POST</td>
</tr>
<tr>
<td>Read</td>
<td>GET</td>
</tr>
<tr>
<td>Update</td>
<td>PUT</td>
</tr>
<tr>
<td>Delete</td>
<td>DELETE</td>
</tr>
</tbody></table>
<hr />
<h1>1. GET Request</h1>
<p>Used for:</p>
<pre><code class="language-id=&quot;rest009&quot;">Fetching data
</code></pre>
<p>Example:</p>
<pre><code class="language-id=&quot;rest010&quot;">GET /users
</code></pre>
<p>Fetches all users.</p>
<hr />
<h2>Express Example</h2>
<pre><code class="language-javascript">app.get("/users", (req, res) =&gt; {
  res.send("All users");
});
</code></pre>
<hr />
<h1>2. POST Request</h1>
<p>Used for:</p>
<pre><code class="language-id=&quot;rest012&quot;">Creating new data
</code></pre>
<p>Example:</p>
<pre><code class="language-id=&quot;rest013&quot;">POST /users
</code></pre>
<p>Creates a new user.</p>
<hr />
<h2>Express Example</h2>
<pre><code class="language-javascript">app.post("/users", (req, res) =&gt; {
  res.send("User created");
});
</code></pre>
<hr />
<h1>3. PUT Request</h1>
<p>Used for:</p>
<pre><code class="language-id=&quot;rest015&quot;">Updating existing data
</code></pre>
<p>Example:</p>
<pre><code class="language-id=&quot;rest016&quot;">PUT /users/1
</code></pre>
<p>Updates user with ID:</p>
<pre><code class="language-id=&quot;rest017&quot;">1
</code></pre>
<hr />
<h2>Express Example</h2>
<pre><code class="language-javascript">app.put("/users/:id", (req, res) =&gt; {
  res.send("User updated");
});
</code></pre>
<hr />
<h1>4. DELETE Request</h1>
<p>Used for:</p>
<pre><code class="language-id=&quot;rest019&quot;">Removing data
</code></pre>
<p>Example:</p>
<pre><code class="language-id=&quot;rest020&quot;">DELETE /users/1
</code></pre>
<p>Deletes user with ID:</p>
<pre><code class="language-id=&quot;rest021&quot;">1
</code></pre>
<hr />
<h2>Express Example</h2>
<pre><code class="language-javascript">app.delete("/users/:id", (req, res) =&gt; {
  res.send("User deleted");
});
</code></pre>
<hr />
<h1>REST Route Design Principles</h1>
<p>REST APIs follow clean route naming conventions.</p>
<hr />
<h1>Good REST Routes</h1>
<pre><code class="language-id=&quot;rest023&quot;">/users
/users/1
/products
/orders
</code></pre>
<hr />
<h1>Avoid Verb-Based Routes</h1>
<p>Avoid routes like:</p>
<pre><code class="language-id=&quot;rest024&quot;">/getUsers
/createUser
/deleteUser
</code></pre>
<p>HTTP methods already define the action.</p>
<hr />
<h1>Understanding Resource IDs</h1>
<p>Example:</p>
<pre><code class="language-id=&quot;rest025&quot;">/users/10
</code></pre>
<p>Here:</p>
<pre><code class="language-id=&quot;rest026&quot;">10
</code></pre>
<p>represents a specific user resource.</p>
<hr />
<h1>REST Request-Response Lifecycle</h1>
<pre><code class="language-id=&quot;rest027&quot;">Client Request
       ↓
Express Route
       ↓
Business Logic
       ↓
Database
       ↓
Response Sent
</code></pre>
<hr />
<h1>Example Users API</h1>
<p>Let’s design a simple REST API for users.</p>
<hr />
<h1>Get All Users</h1>
<pre><code class="language-javascript">app.get("/users", (req, res) =&gt; {
  res.send("Fetching all users");
});
</code></pre>
<hr />
<h1>Get Single User</h1>
<pre><code class="language-javascript">app.get("/users/:id", (req, res) =&gt; {
  res.send(`User ID: ${req.params.id}`);
});
</code></pre>
<hr />
<h1>Create User</h1>
<pre><code class="language-javascript">app.post("/users", (req, res) =&gt; {
  res.send("Creating user");
});
</code></pre>
<hr />
<h1>Update User</h1>
<pre><code class="language-javascript">app.put("/users/:id", (req, res) =&gt; {
  res.send("Updating user");
});
</code></pre>
<hr />
<h1>Delete User</h1>
<pre><code class="language-javascript">app.delete("/users/:id", (req, res) =&gt; {
  res.send("Deleting user");
});
</code></pre>
<hr />
<h1>Status Codes Basics</h1>
<p>Servers send status codes to indicate request result.</p>
<hr />
<h1>Common Status Codes</h1>
<table>
<thead>
<tr>
<th>Status Code</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>200</td>
<td>Success</td>
</tr>
<tr>
<td>201</td>
<td>Resource Created</td>
</tr>
<tr>
<td>400</td>
<td>Bad Request</td>
</tr>
<tr>
<td>401</td>
<td>Unauthorized</td>
</tr>
<tr>
<td>404</td>
<td>Resource Not Found</td>
</tr>
<tr>
<td>500</td>
<td>Server Error</td>
</tr>
</tbody></table>
<hr />
<h1>Example Using Status Codes</h1>
<pre><code class="language-javascript">app.post("/users", (req, res) =&gt; {
  res.status(201).send("User created");
});
</code></pre>
<hr />
<h1>Why Status Codes Matter</h1>
<p>Status codes help clients understand:</p>
<ul>
<li><p>success</p>
</li>
<li><p>failure</p>
</li>
<li><p>missing data</p>
</li>
<li><p>authentication problems</p>
</li>
</ul>
<p>without reading long messages.</p>
<hr />
<h1>REST API Naming Best Practices</h1>
<hr />
<h2>Use Nouns</h2>
<p>Good:</p>
<pre><code class="language-id=&quot;rest034&quot;">/users
</code></pre>
<p>Bad:</p>
<pre><code class="language-id=&quot;rest035&quot;">/getUsers
</code></pre>
<hr />
<h2>Keep Routes Consistent</h2>
<p>Follow same pattern everywhere.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;rest036&quot;">/users
/products
/orders
</code></pre>
<hr />
<h2>Use Plural Resource Names</h2>
<p>Usually preferred:</p>
<pre><code class="language-id=&quot;rest037&quot;">/users
</code></pre>
<p>instead of:</p>
<pre><code class="language-id=&quot;rest038&quot;">/user
</code></pre>
<hr />
<h1>Real-World REST Example</h1>
<p>Imagine Instagram.</p>
<p>Possible APIs:</p>
<pre><code class="language-id=&quot;rest039&quot;">GET /posts
POST /posts
GET /users
DELETE /comments/10
</code></pre>
<p>REST principles help organize large systems cleanly.</p>
<hr />
<h1>Why REST APIs Became Popular</h1>
<p>REST APIs are popular because they are:</p>
<p>✅ Simple ✅ Scalable ✅ Easy to understand ✅ Language independent ✅ Frontend friendly</p>
<p>Almost every modern application uses APIs.</p>
<hr />
<h1>Common Beginner Mistakes</h1>
<h2>Using Wrong HTTP Methods</h2>
<p>Example:</p>
<p>Using:</p>
<pre><code class="language-id=&quot;rest040&quot;">GET
</code></pre>
<p>for deleting data is incorrect.</p>
<hr />
<h2>Poor Route Naming</h2>
<p>Avoid:</p>
<pre><code class="language-id=&quot;rest041&quot;">/createProduct
</code></pre>
<p>Use:</p>
<pre><code class="language-id=&quot;rest042&quot;">POST /products
</code></pre>
<p>instead.</p>
<hr />
<h2>Ignoring Status Codes</h2>
<p>Always send proper responses.</p>
<hr />
<h1>Practice Assignment</h1>
<p>Try these exercises yourself.</p>
<hr />
<h1>1. Create Express Server</h1>
<p>Setup a basic Express application.</p>
<hr />
<h1>2. Create Users Routes</h1>
<p>Add routes for:</p>
<ul>
<li><p>GET</p>
</li>
<li><p>POST</p>
</li>
<li><p>PUT</p>
</li>
<li><p>DELETE</p>
</li>
</ul>
<hr />
<h1>3. Use Route Parameters</h1>
<p>Access user ID using:</p>
<pre><code class="language-javascript">req.params.id
</code></pre>
<hr />
<h1>4. Send Status Codes</h1>
<p>Use:</p>
<pre><code class="language-javascript">res.status()
</code></pre>
<p>inside responses.</p>
<hr />
<h1>5. Design Another Resource</h1>
<p>Create REST routes for:</p>
<pre><code class="language-id=&quot;rest045&quot;">/products
</code></pre>
<p>or:</p>
<pre><code class="language-id=&quot;rest046&quot;">/movies
</code></pre>
<hr />
<h1>Final Thoughts</h1>
<p>REST APIs are the foundation of modern backend development.</p>
<p>They help applications communicate using:</p>
<ul>
<li><p>clean routes</p>
</li>
<li><p>HTTP methods</p>
</li>
<li><p>structured responses</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;rest047&quot;">REST APIs organize backend functionality around resources.
</code></pre>
<p>Understanding REST API design is extremely important for:</p>
<ul>
<li><p>frontend developers</p>
</li>
<li><p>backend engineers</p>
</li>
<li><p>full-stack development</p>
</li>
<li><p>scalable application architecture</p>
</li>
</ul>
<p>As you continue learning Express.js and backend development, REST principles will become a core part of building professional APIs.</p>
<hr />
<p>And now, you know how REST API design works with Express.js.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript: Try, Catch, Finally]]></title><description><![CDATA[While writing JavaScript programs, errors are completely normal.
Even experienced developers encounter errors every day.
The important part is not avoiding errors completely, but handling them properl]]></description><link>https://blogs.abhishekdogra.in/error-handling-in-javascript-try-catch-finally</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/error-handling-in-javascript-try-catch-finally</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:35:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/32a88d1b-c68a-4815-b460-093758e94eff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While writing JavaScript programs, errors are completely normal.</p>
<p>Even experienced developers encounter errors every day.</p>
<p>The important part is not avoiding errors completely, but handling them properly.</p>
<p>Without error handling:</p>
<ul>
<li><p>applications can crash</p>
</li>
<li><p>users may see broken pages</p>
</li>
<li><p>debugging becomes difficult</p>
</li>
</ul>
<p>JavaScript provides tools like:</p>
<ul>
<li><p><code>try</code></p>
</li>
<li><p><code>catch</code></p>
</li>
<li><p><code>finally</code></p>
</li>
<li><p><code>throw</code></p>
</li>
</ul>
<p>to manage errors gracefully.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What errors are in JavaScript</p>
</li>
<li><p>Using try and catch blocks</p>
</li>
<li><p>The finally block</p>
</li>
<li><p>Throwing custom errors</p>
</li>
<li><p>Why error handling matters</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h2>What Are Errors in JavaScript?</h2>
<p>Errors are problems that occur while code is running.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log(userName);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err002&quot;">ReferenceError: userName is not defined
</code></pre>
<p>JavaScript stops execution when it encounters an unhandled error.</p>
<hr />
<h2>Why Errors Happen</h2>
<p>Errors can occur because of:</p>
<ul>
<li><p>wrong variable names</p>
</li>
<li><p>invalid operations</p>
</li>
<li><p>API failures</p>
</li>
<li><p>network issues</p>
</li>
<li><p>incorrect user input</p>
</li>
</ul>
<p>Errors are a natural part of programming.</p>
<hr />
<h2>Runtime Errors</h2>
<p>Some errors happen while the program is running.</p>
<p>These are called:</p>
<pre><code class="language-id=&quot;err003&quot;">Runtime Errors
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">let user = null;

console.log(user.name);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err005&quot;">TypeError
</code></pre>
<p>because we cannot access properties of <code>null</code>.</p>
<hr />
<h2>Why Error Handling Matters</h2>
<p>Without proper handling:</p>
<pre><code class="language-id=&quot;err006&quot;">Error occurs
     ↓
Program crashes
</code></pre>
<p>With error handling:</p>
<pre><code class="language-id=&quot;err007&quot;">Error occurs
     ↓
Program handles error safely
     ↓
Application continues running
</code></pre>
<p>This is called:</p>
<pre><code class="language-id=&quot;err008&quot;">Graceful Failure
</code></pre>
<hr />
<h2>What Is <code>try</code>?</h2>
<p>The <code>try</code> block contains code that may produce an error.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  console.log(userName);
}
</code></pre>
<p>JavaScript attempts to execute this code.</p>
<p>If an error occurs, control moves to <code>catch</code>.</p>
<hr />
<h2>What Is <code>catch</code>?</h2>
<p>The <code>catch</code> block handles errors safely.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  console.log(userName);
} catch (error) {
  console.log("Something went wrong");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err011&quot;">Something went wrong
</code></pre>
<p>Instead of crashing, the application handles the error gracefully.</p>
<hr />
<h2>Understanding the Flow</h2>
<pre><code class="language-id=&quot;err012&quot;">try block runs
      ↓
Error occurs?
   ↙       ↘
 No         Yes
 ↓           ↓
Continue    catch block runs
</code></pre>
<hr />
<h2>Accessing Error Information</h2>
<p>The <code>catch</code> block receives an error object.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  console.log(userName);
} catch (error) {
  console.log(error);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err014&quot;">ReferenceError: userName is not defined
</code></pre>
<p>This helps developers debug issues.</p>
<hr />
<h2>Error Handling Flow</h2>
<pre><code class="language-id=&quot;err015&quot;">try
 ↓
Code Executes
 ↓
Error?
 ↙      ↘
No       Yes
↓         ↓
Continue  catch
</code></pre>
<hr />
<h2>The <code>finally</code> Block</h2>
<p>The <code>finally</code> block always executes.</p>
<p>Whether:</p>
<ul>
<li><p>an error occurs</p>
</li>
<li><p>or no error occurs</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">try {
  console.log("Inside try");
} catch (error) {
  console.log("Inside catch");
} finally {
  console.log("Inside finally");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err017&quot;">Inside try
Inside finally
</code></pre>
<hr />
<h2>When <code>finally</code> Is Useful</h2>
<p><code>finally</code> is commonly used for:</p>
<ul>
<li><p>closing database connections</p>
</li>
<li><p>stopping loaders</p>
</li>
<li><p>cleaning resources</p>
</li>
<li><p>logging completion</p>
</li>
</ul>
<p>Because it always runs.</p>
<hr />
<h2>Try → Catch → Finally Order</h2>
<pre><code class="language-id=&quot;err018&quot;">try
 ↓
catch (if error happens)
 ↓
finally (always runs)
</code></pre>
<hr />
<h2>Example with Actual Error</h2>
<pre><code class="language-javascript">try {
  let user = null;

  console.log(user.name);
} catch (error) {
  console.log("Cannot read property");
} finally {
  console.log("Execution completed");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err020&quot;">Cannot read property
Execution completed
</code></pre>
<hr />
<h2>Throwing Custom Errors</h2>
<p>JavaScript also allows developers to create their own errors using:</p>
<pre><code class="language-javascript">throw
</code></pre>
<hr />
<h2>Simple Custom Error Example</h2>
<pre><code class="language-javascript">let age = 15;

try {
  if (age &lt; 18) {
    throw new Error("Age must be 18 or above");
  }

  console.log("Access granted");
} catch (error) {
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;err023&quot;">Age must be 18 or above
</code></pre>
<hr />
<h2>Why Custom Errors Are Useful</h2>
<p>Custom errors help:</p>
<p>✅ Validate user input<br />✅ Prevent invalid operations<br />✅ Provide meaningful messages<br />✅ Improve debugging</p>
<hr />
<h2>Real-World Example</h2>
<p>Imagine a login system.</p>
<p>Flow:</p>
<pre><code class="language-id=&quot;err024&quot;">User enters password
        ↓
Password invalid?
     ↙        ↘
   Yes         No
    ↓           ↓
Show Error    Login Success
</code></pre>
<p>Applications constantly use error handling like this.</p>
<hr />
<h2>Common Types of JavaScript Errors</h2>
<table>
<thead>
<tr>
<th>Error Type</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>ReferenceError</td>
<td>Variable does not exist</td>
</tr>
<tr>
<td>TypeError</td>
<td>Invalid operation on value</td>
</tr>
<tr>
<td>SyntaxError</td>
<td>Incorrect syntax</td>
</tr>
<tr>
<td>RangeError</td>
<td>Value out of allowed range</td>
</tr>
</tbody></table>
<hr />
<h2>Example of Syntax Error</h2>
<pre><code class="language-javascript">if(true {
  console.log("Hello");
}
</code></pre>
<p>Missing bracket causes:</p>
<pre><code class="language-id=&quot;err026&quot;">SyntaxError
</code></pre>
<hr />
<h2>Graceful Failure Example</h2>
<p>Without handling:</p>
<pre><code class="language-id=&quot;err027&quot;">Application crashes
</code></pre>
<p>With handling:</p>
<pre><code class="language-id=&quot;err028&quot;">User sees friendly message
</code></pre>
<p>This creates better user experience.</p>
<hr />
<h2>Common Beginner Mistakes</h2>
<h3>Ignoring Errors</h3>
<p>Never leave errors unhandled in real applications.</p>
<hr />
<h3>Empty Catch Blocks</h3>
<p>Avoid this:</p>
<pre><code class="language-javascript">catch(error) {}
</code></pre>
<p>Always log or handle the error properly.</p>
<hr />
<h3>Using <code>try-catch</code> Everywhere</h3>
<p>Use it where errors are actually expected.</p>
<p>Too much error handling can reduce readability.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Handle Undefined Variable Error</h2>
<p>Use:</p>
<pre><code class="language-javascript">try-catch
</code></pre>
<p>to handle a variable error.</p>
<hr />
<h2>2. Use <code>finally</code></h2>
<p>Print a message inside <code>finally</code>.</p>
<p>Observe that it always runs.</p>
<hr />
<h2>3. Throw Custom Error</h2>
<p>Create an age validation example using:</p>
<pre><code class="language-javascript">throw
</code></pre>
<hr />
<h2>4. Print Error Message</h2>
<p>Use:</p>
<pre><code class="language-javascript">error.message
</code></pre>
<p>inside <code>catch</code>.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Errors are an unavoidable part of programming.</p>
<p>Strong developers are not people who never face errors.</p>
<p>They are people who:</p>
<ul>
<li><p>understand errors</p>
</li>
<li><p>debug effectively</p>
</li>
<li><p>handle failures gracefully</p>
</li>
</ul>
<p>JavaScript’s:</p>
<ul>
<li><p><code>try</code></p>
</li>
<li><p><code>catch</code></p>
</li>
<li><p><code>finally</code></p>
</li>
<li><p><code>throw</code></p>
</li>
</ul>
<p>provide powerful tools for managing runtime issues safely.</p>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;err033&quot;">Good applications don't crash easily.
They handle errors gracefully.
</code></pre>
<p>Understanding error handling is essential for building:</p>
<ul>
<li><p>reliable applications</p>
</li>
<li><p>production-ready systems</p>
</li>
<li><p>professional backend and frontend projects</p>
</li>
</ul>
<p>As you continue learning JavaScript, proper error handling will become one of your most important skills.</p>
<hr />
<p>And now, you know what Error Handling in JavaScript is.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[JavaScript introduced the spread and rest operators to make working with arrays, objects, and function arguments much easier.
Both operators use the same syntax:
...

But depending on where and how th]]></description><link>https://blogs.abhishekdogra.in/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/spread-vs-rest-operators-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:34:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/b4ed2dfb-124d-4e37-9d16-6953f07e220f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript introduced the spread and rest operators to make working with arrays, objects, and function arguments much easier.</p>
<p>Both operators use the same syntax:</p>
<pre><code class="language-javascript">...
</code></pre>
<p>But depending on where and how they are used, they behave differently.</p>
<p>This often confuses beginners.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What the spread operator does</p>
</li>
<li><p>What the rest operator does</p>
</li>
<li><p>Differences between spread and rest</p>
</li>
<li><p>Using spread with arrays and objects</p>
</li>
<li><p>Practical real-world use cases</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h2>Understanding the <code>...</code> Syntax</h2>
<p>The three dots syntax:</p>
<pre><code class="language-javascript">...
</code></pre>
<p>can either:</p>
<ul>
<li><p>expand values → Spread</p>
</li>
<li><p>collect values → Rest</p>
</li>
</ul>
<p>The behavior depends on the context.</p>
<hr />
<h2>What Is the Spread Operator?</h2>
<p>The spread operator is used to:</p>
<pre><code class="language-id=&quot;spr003&quot;">Expand values
</code></pre>
<p>It takes elements from an array or object and spreads them out individually.</p>
<hr />
<h2>Spread Operator with Arrays</h2>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3];

console.log(...numbers);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;spr005&quot;">1 2 3
</code></pre>
<p>The array elements are expanded individually.</p>
<hr />
<h2>Spread Visualization</h2>
<pre><code class="language-id=&quot;spr006&quot;">[1, 2, 3]
     ↓
...numbers
     ↓
1, 2, 3
</code></pre>
<p>Spread breaks elements apart.</p>
<hr />
<h2>Copying Arrays Using Spread</h2>
<p>Example:</p>
<pre><code class="language-javascript">const arr1 = [1, 2, 3];

const arr2 = [...arr1];

console.log(arr2);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">[1, 2, 3]
</code></pre>
<p>This creates a shallow copy of the array.</p>
<hr />
<h2>Merging Arrays</h2>
<p>Example:</p>
<pre><code class="language-javascript">const a = [1, 2];
const b = [3, 4];

const result = [...a, ...b];

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<p>This is much cleaner than older methods.</p>
<hr />
<h2>Spread with Objects</h2>
<p>Spread also works with objects.</p>
<p>Example:</p>
<pre><code class="language-javascript">const user = {
  name: "Rahul",
  age: 22
};

const updatedUser = {
  ...user,
  city: "Delhi"
};

console.log(updatedUser);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{
  name: "Rahul",
  age: 22,
  city: "Delhi"
}
</code></pre>
<hr />
<h2>Object Spread Visualization</h2>
<pre><code class="language-id=&quot;spr013&quot;">user object
     ↓
Spread properties
     ↓
New object created
</code></pre>
<hr />
<h2>Updating Object Properties</h2>
<p>Example:</p>
<pre><code class="language-javascript">const user = {
  name: "Rahul",
  age: 22
};

const updatedUser = {
  ...user,
  age: 23
};

console.log(updatedUser);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{
  name: "Rahul",
  age: 23
}
</code></pre>
<p>The new value overrides the old one.</p>
<hr />
<h2>What Is the Rest Operator?</h2>
<p>The rest operator is used to:</p>
<pre><code class="language-id=&quot;spr016&quot;">Collect multiple values into one
</code></pre>
<p>Instead of expanding values, it gathers them together.</p>
<hr />
<h2>Rest Operator in Functions</h2>
<p>Example:</p>
<pre><code class="language-javascript">function sum(...numbers) {
  console.log(numbers);
}

sum(1, 2, 3, 4);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<p>The rest operator collects all arguments into an array.</p>
<hr />
<h2>Rest Visualization</h2>
<pre><code class="language-id=&quot;spr019&quot;">1, 2, 3, 4
     ↓
...numbers
     ↓
[1, 2, 3, 4]
</code></pre>
<p>Rest groups values together.</p>
<hr />
<h2>Using Rest for Flexible Functions</h2>
<p>Example:</p>
<pre><code class="language-javascript">function total(...nums) {
  let sum = 0;

  for (let num of nums) {
    sum += num;
  }

  return sum;
}

console.log(total(1, 2, 3));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;spr021&quot;">6
</code></pre>
<p>This allows functions to accept any number of arguments.</p>
<hr />
<h2>Rest with Array Destructuring</h2>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3, 4];

const [first, ...rest] = numbers;

console.log(first);
console.log(rest);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;spr023&quot;">1
[2, 3, 4]
</code></pre>
<p>Here:</p>
<ul>
<li><p>first value goes into <code>first</code></p>
</li>
<li><p>remaining values go into <code>rest</code></p>
</li>
</ul>
<hr />
<h2>Spread vs Rest</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Spread</th>
<th>Rest</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Expands values</td>
<td>Collects values</td>
</tr>
<tr>
<td>Direction</td>
<td>Break apart</td>
<td>Gather together</td>
</tr>
<tr>
<td>Common Usage</td>
<td>Arrays, objects</td>
<td>Function arguments</td>
</tr>
<tr>
<td>Result</td>
<td>Individual elements</td>
<td>Single array/object</td>
</tr>
</tbody></table>
<hr />
<h2>Simple Comparison</h2>
<h3>Spread</h3>
<pre><code class="language-javascript">const arr = [1, 2, 3];

console.log(...arr);
</code></pre>
<p>Expands values.</p>
<hr />
<h3>Rest</h3>
<pre><code class="language-javascript">function test(...args) {
  console.log(args);
}
</code></pre>
<p>Collects values.</p>
<hr />
<h2>Real-World Use Cases of Spread</h2>
<h3>Copying Arrays</h3>
<pre><code class="language-javascript">const copy = [...original];
</code></pre>
<hr />
<h3>Merging Arrays</h3>
<pre><code class="language-javascript">const merged = [...a, ...b];
</code></pre>
<hr />
<h3>Updating React State</h3>
<pre><code class="language-javascript">setUser({
  ...user,
  age: 25
});
</code></pre>
<p>Very common in React applications.</p>
<hr />
<h2>Real-World Use Cases of Rest</h2>
<h3>Unlimited Function Arguments</h3>
<pre><code class="language-javascript">function log(...messages) {}
</code></pre>
<hr />
<h3>Collect Remaining Values</h3>
<pre><code class="language-javascript">const [first, ...others] = arr;
</code></pre>
<p>Useful in destructuring.</p>
<hr />
<h2>Common Beginner Mistakes</h2>
<h3>Confusing Spread and Rest</h3>
<p>Remember:</p>
<pre><code class="language-id=&quot;spr031&quot;">Spread → Expands
Rest → Collects
</code></pre>
<hr />
<h3>Forgetting Rest Must Be Last</h3>
<p>Wrong:</p>
<pre><code class="language-javascript">const [...rest, last] = arr;
</code></pre>
<p>Correct:</p>
<pre><code class="language-javascript">const [first, ...rest] = arr;
</code></pre>
<p>Rest element must be last.</p>
<hr />
<h3>Thinking Spread Creates Deep Copy</h3>
<p>Spread creates only a shallow copy.</p>
<p>Nested objects are still shared.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Copy an Array</h2>
<p>Use spread to create a copy.</p>
<hr />
<h2>2. Merge Two Arrays</h2>
<p>Combine arrays using:</p>
<pre><code class="language-javascript">...
</code></pre>
<hr />
<h2>3. Create Flexible Sum Function</h2>
<p>Use rest operator to accept unlimited numbers.</p>
<hr />
<h2>4. Use Object Spread</h2>
<p>Add a new property to an existing object.</p>
<hr />
<h2>5. Use Array Destructuring</h2>
<p>Extract first value and remaining values separately.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Spread and rest operators are some of the most useful modern JavaScript features.</p>
<p>They help developers write:</p>
<ul>
<li><p>cleaner code</p>
</li>
<li><p>shorter code</p>
</li>
<li><p>more readable code</p>
</li>
</ul>
<p>The key difference is:</p>
<pre><code class="language-id=&quot;spr035&quot;">Spread → expands values
Rest → collects values
</code></pre>
<p>Understanding these operators is extremely important because they are widely used in:</p>
<ul>
<li><p>React</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>APIs</p>
</li>
<li><p>Array manipulation</p>
</li>
<li><p>Object updates</p>
</li>
<li><p>Modern JavaScript applications</p>
</li>
</ul>
<p>Once you get comfortable with them, your JavaScript code becomes much cleaner and more professional.</p>
<hr />
<p>And now, you know what Spread and Rest Operators in JavaScript are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[String Polyfills and Common Interview Methods in JavaScript

]]></title><description><![CDATA[Strings are one of the most commonly used data types in JavaScript.
We use strings for:

User names

Messages

API responses

Search functionality

Form validation


JavaScript provides many built-in ]]></description><link>https://blogs.abhishekdogra.in/string-polyfills-and-common-interview-methods-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/string-polyfills-and-common-interview-methods-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:32:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/9d9a9d9f-0065-4b69-aff9-0023e3ccca98.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Strings are one of the most commonly used data types in JavaScript.</p>
<p>We use strings for:</p>
<ul>
<li><p>User names</p>
</li>
<li><p>Messages</p>
</li>
<li><p>API responses</p>
</li>
<li><p>Search functionality</p>
</li>
<li><p>Form validation</p>
</li>
</ul>
<p>JavaScript provides many built-in string methods to make working with strings easier.</p>
<p>But in interviews, developers are often asked:</p>
<pre><code class="language-id=&quot;str001&quot;">"Can you implement this method yourself?"
</code></pre>
<p>This is where:</p>
<ul>
<li><p>String utilities</p>
</li>
<li><p>Polyfills</p>
</li>
<li><p>Custom implementations</p>
</li>
</ul>
<p>become important.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What string methods are</p>
</li>
<li><p>Why developers write polyfills</p>
</li>
<li><p>Implementing simple string utilities</p>
</li>
<li><p>Common interview string problems</p>
</li>
<li><p>Why understanding built-in behavior matters</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>What Are String Methods?</h1>
<p>String methods are built-in functions provided by JavaScript to work with strings.</p>
<p>Examples include:</p>
<ul>
<li><p><code>toUpperCase()</code></p>
</li>
<li><p><code>toLowerCase()</code></p>
</li>
<li><p><code>includes()</code></p>
</li>
<li><p><code>split()</code></p>
</li>
<li><p><code>trim()</code></p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">let name = "rahul";

console.log(name.toUpperCase());
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str003&quot;">RAHUL
</code></pre>
<p>These methods make string processing easier.</p>
<hr />
<h1>Why Developers Write Polyfills</h1>
<p>A polyfill is a custom implementation of a built-in method.</p>
<p>In simple words:</p>
<pre><code class="language-id=&quot;str004&quot;">Recreating built-in behavior manually
</code></pre>
<p>Developers write polyfills to:</p>
<p>✅ Understand internal logic ✅ Prepare for interviews ✅ Support older environments ✅ Improve problem-solving skills</p>
<hr />
<h1>Understanding Built-In Behavior</h1>
<p>When you use:</p>
<pre><code class="language-javascript">str.toUpperCase()
</code></pre>
<p>JavaScript internally performs logic to convert characters.</p>
<p>Polyfills help us understand:</p>
<pre><code class="language-id=&quot;str006&quot;">How built-in methods actually work
</code></pre>
<p>This improves JavaScript fundamentals significantly.</p>
<hr />
<h1>String Processing Flow</h1>
<pre><code class="language-id=&quot;str007&quot;">Input String
      ↓
Method Logic Applied
      ↓
New Processed String Returned
</code></pre>
<p>Most string methods follow this pattern.</p>
<hr />
<h1>Simple String Utility Example</h1>
<p>Suppose we want to count characters manually.</p>
<p>Example:</p>
<pre><code class="language-javascript">function countCharacters(str) {
  let count = 0;

  for (let char of str) {
    count++;
  }

  return count;
}

console.log(countCharacters("JavaScript"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str009&quot;">10
</code></pre>
<p>This helps understand how string traversal works internally.</p>
<hr />
<h1>Polyfill Example: Custom includes()</h1>
<p>JavaScript already has:</p>
<pre><code class="language-javascript">includes()
</code></pre>
<p>But let’s implement a simplified version ourselves.</p>
<hr />
<h1>Custom <code>includes()</code> Implementation</h1>
<p>Example:</p>
<pre><code class="language-javascript">function myIncludes(str, word) {
  return str.indexOf(word) !== -1;
}

console.log(myIncludes("JavaScript", "Script"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str012&quot;">true
</code></pre>
<p>This recreates basic behavior of <code>includes()</code>.</p>
<hr />
<h1>Polyfill Behavior Representation</h1>
<pre><code class="language-id=&quot;str013&quot;">String Input
     ↓
Search Logic Runs
     ↓
Word Found?
   ↙      ↘
true      false
</code></pre>
<hr />
<h1>Custom Reverse String Function</h1>
<p>This is a very common interview question.</p>
<p>Example:</p>
<pre><code class="language-javascript">function reverseString(str) {
  let reversed = "";

  for (let i = str.length - 1; i &gt;= 0; i--) {
    reversed += str[i];
  }

  return reversed;
}

console.log(reverseString("hello"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str015&quot;">olleh
</code></pre>
<hr />
<h1>Understanding the Logic</h1>
<p>Flow:</p>
<pre><code class="language-id=&quot;str016&quot;">Start from last character
        ↓
Move backward
        ↓
Build new string
</code></pre>
<p>This develops problem-solving thinking.</p>
<hr />
<h1>Custom Palindrome Checker</h1>
<p>Another common interview problem.</p>
<p>A palindrome reads the same forward and backward.</p>
<p>Examples:</p>
<pre><code class="language-id=&quot;str017&quot;">madam
racecar
</code></pre>
<hr />
<h1>Palindrome Example</h1>
<pre><code class="language-javascript">function isPalindrome(str) {
  let reversed = str.split("").reverse().join("");

  return str === reversed;
}

console.log(isPalindrome("madam"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str019&quot;">true
</code></pre>
<hr />
<h1>Common Interview String Problems</h1>
<p>String questions are extremely common in interviews.</p>
<p>Popular examples include:</p>
<ul>
<li><p>Reverse a string</p>
</li>
<li><p>Check palindrome</p>
</li>
<li><p>Count characters</p>
</li>
<li><p>Find duplicates</p>
</li>
<li><p>Capitalize words</p>
</li>
<li><p>Check anagrams</p>
</li>
<li><p>Remove spaces</p>
</li>
</ul>
<p>These problems test:</p>
<p>✅ Loops ✅ Logic building ✅ String manipulation ✅ Problem-solving ability</p>
<hr />
<h1>Custom capitalize() Function</h1>
<p>Example:</p>
<pre><code class="language-javascript">function capitalize(str) {
  return str[0].toUpperCase() + str.slice(1);
}

console.log(capitalize("javascript"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str021&quot;">Javascript
</code></pre>
<hr />
<h1>Why Interviewers Ask Polyfill Questions</h1>
<p>Interviewers want to know:</p>
<ul>
<li><p>Can you think logically?</p>
</li>
<li><p>Do you understand built-in behavior?</p>
</li>
<li><p>Can you solve problems manually?</p>
</li>
</ul>
<p>Because using methods is easy.</p>
<p>Understanding:</p>
<pre><code class="language-id=&quot;str022&quot;">How they work internally
</code></pre>
<p>shows deeper JavaScript knowledge.</p>
<hr />
<h1>Built-In Method vs Manual Logic</h1>
<h3>Built-In Version</h3>
<pre><code class="language-javascript">str.reverse()
</code></pre>
<p>Easy to use.</p>
<hr />
<h3>Manual Logic</h3>
<pre><code class="language-javascript">Loop through characters manually
</code></pre>
<p>Shows understanding of algorithms and logic.</p>
<hr />
<h1>Important String Methods to Know</h1>
<table>
<thead>
<tr>
<th>Method</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>includes()</code></td>
<td>Check substring</td>
</tr>
<tr>
<td><code>split()</code></td>
<td>Convert string to array</td>
</tr>
<tr>
<td><code>join()</code></td>
<td>Convert array to string</td>
</tr>
<tr>
<td><code>slice()</code></td>
<td>Extract part of string</td>
</tr>
<tr>
<td><code>trim()</code></td>
<td>Remove spaces</td>
</tr>
<tr>
<td><code>toUpperCase()</code></td>
<td>Uppercase conversion</td>
</tr>
<tr>
<td><code>toLowerCase()</code></td>
<td>Lowercase conversion</td>
</tr>
</tbody></table>
<p>These methods appear frequently in interviews.</p>
<hr />
<h1>Common Beginner Mistakes</h1>
<h3>Forgetting Strings Are Immutable</h3>
<p>Strings cannot be changed directly.</p>
<p>Example:</p>
<pre><code class="language-javascript">str[0] = "H";
</code></pre>
<p>does not modify the original string.</p>
<hr />
<h3>Confusing Array and String Methods</h3>
<p>Some methods belong only to arrays.</p>
<p>Example:</p>
<pre><code class="language-javascript">reverse()
</code></pre>
<p>works on arrays, not directly on strings.</p>
<hr />
<h3>Ignoring Edge Cases</h3>
<p>Always think about:</p>
<ul>
<li><p>Empty strings</p>
</li>
<li><p>Spaces</p>
</li>
<li><p>Uppercase/lowercase differences</p>
</li>
</ul>
<p>Interviewers often test edge cases.</p>
<hr />
<h1>Practice Assignment</h1>
<p>Try these problems yourself.</p>
<hr />
<h1>1. Reverse a String</h1>
<p>Input:</p>
<pre><code class="language-id=&quot;str027&quot;">hello
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str028&quot;">olleh
</code></pre>
<hr />
<h1>2. Check Palindrome</h1>
<p>Input:</p>
<pre><code class="language-id=&quot;str029&quot;">madam
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;str030&quot;">true
</code></pre>
<hr />
<h1>3. Count Vowels</h1>
<p>Count:</p>
<pre><code class="language-id=&quot;str031&quot;">a, e, i, o, u
</code></pre>
<p>inside a string.</p>
<hr />
<h1>4. Create Your Own includes()</h1>
<p>Implement a simplified version manually.</p>
<hr />
<h1>5. Capitalize First Letter</h1>
<p>Convert:</p>
<pre><code class="language-id=&quot;str032&quot;">javascript
</code></pre>
<p>to:</p>
<pre><code class="language-id=&quot;str033&quot;">Javascript
</code></pre>
<hr />
<h1>Final Thoughts</h1>
<p>String manipulation is one of the most important JavaScript skills.</p>
<p>Understanding:</p>
<ul>
<li><p>built-in methods</p>
</li>
<li><p>polyfills</p>
</li>
<li><p>manual implementations</p>
</li>
</ul>
<p>helps you become much stronger in:</p>
<ul>
<li><p>interviews</p>
</li>
<li><p>debugging</p>
</li>
<li><p>problem solving</p>
</li>
<li><p>JavaScript fundamentals</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;str034&quot;">Don't just use methods.
Understand how they work internally.
</code></pre>
<p>That mindset separates beginner developers from strong problem solvers.</p>
<p>As you continue learning JavaScript, practicing string problems will greatly improve your coding confidence and interview performance.</p>
<hr />
<p>And now, you know what String Polyfills and Common Interview Methods in JavaScript are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Setting Up Your First Node.js Application Step-by-Step

]]></title><description><![CDATA[If you want to become a backend developer, Node.js is one of the best technologies to learn.
With Node.js, you can:

Build servers

Create APIs

Work with databases

Build real-time applications

Use ]]></description><link>https://blogs.abhishekdogra.in/setting-up-your-first-node-js-application-step-by-step</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/setting-up-your-first-node-js-application-step-by-step</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:29:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/ad7aa8a4-c766-4171-8df0-f3a3f88dcecf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you want to become a backend developer, Node.js is one of the best technologies to learn.</p>
<p>With Node.js, you can:</p>
<ul>
<li><p>Build servers</p>
</li>
<li><p>Create APIs</p>
</li>
<li><p>Work with databases</p>
</li>
<li><p>Build real-time applications</p>
</li>
<li><p>Use JavaScript outside the browser</p>
</li>
</ul>
<p>In this article, we’ll set up our very first Node.js application step-by-step.</p>
<p>We’ll cover:</p>
<ul>
<li><p>Installing Node.js</p>
</li>
<li><p>Checking installation using terminal</p>
</li>
<li><p>Understanding Node REPL</p>
</li>
<li><p>Creating your first JavaScript file</p>
</li>
<li><p>Running scripts using the <code>node</code> command</p>
</li>
<li><p>Writing a simple Hello World server</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h1>What Is Node.js?</h1>
<p>Node.js is a JavaScript runtime that allows JavaScript to run outside the browser.</p>
<p>Normally, JavaScript runs inside browsers like:</p>
<ul>
<li><p>Chrome</p>
</li>
<li><p>Firefox</p>
</li>
<li><p>Edge</p>
</li>
</ul>
<p>But Node.js allows JavaScript to run directly on your computer or server.</p>
<p>This makes backend development possible using JavaScript.</p>
<hr />
<h1>Step 1: Installing Node.js</h1>
<p>To use Node.js, first install it on your system.</p>
<p>Download Node.js from the official website:</p>
<p><a href="https://nodejs.org?utm_source=chatgpt.com">Node.js Official Website</a></p>
<p>Install the:</p>
<pre><code class="language-id=&quot;jlwm201&quot;">LTS (Long Term Support) version
</code></pre>
<p>because it is stable and recommended for beginners.</p>
<hr />
<h1>What Gets Installed?</h1>
<p>When you install Node.js, two important things are installed:</p>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Node.js</td>
<td>Runs JavaScript outside browser</td>
</tr>
<tr>
<td>npm</td>
<td>Package manager for installing libraries</td>
</tr>
</tbody></table>
<hr />
<h1>Step 2: Check Installation</h1>
<p>After installation, open your terminal or command prompt.</p>
<p>Run:</p>
<pre><code class="language-bash">node -v
</code></pre>
<p>Example output:</p>
<pre><code class="language-id=&quot;jlwm203&quot;">v22.0.0
</code></pre>
<p>This confirms Node.js is installed successfully.</p>
<p>Now check npm:</p>
<pre><code class="language-bash">npm -v
</code></pre>
<p>Example output:</p>
<pre><code class="language-id=&quot;jlwm205&quot;">10.5.0
</code></pre>
<hr />
<h1>Understanding the Terminal</h1>
<p>The terminal is where we run Node.js commands.</p>
<p>Examples:</p>
<pre><code class="language-bash">node app.js
npm install
</code></pre>
<p>Backend developers use the terminal very frequently.</p>
<hr />
<h1>Step 3: Understanding Node REPL</h1>
<p>REPL stands for:</p>
<pre><code class="language-id=&quot;jlwm207&quot;">Read
Evaluate
Print
Loop
</code></pre>
<p>It is an interactive environment where Node.js executes JavaScript instantly.</p>
<p>Start REPL by typing:</p>
<pre><code class="language-bash">node
</code></pre>
<p>You’ll see something like:</p>
<pre><code class="language-id=&quot;jlwm209&quot;">&gt;
</code></pre>
<p>Now you can run JavaScript directly.</p>
<p>Example:</p>
<pre><code class="language-javascript">2 + 3
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm211&quot;">5
</code></pre>
<hr />
<h1>Why REPL Is Useful</h1>
<p>REPL is great for:</p>
<p>✅ Testing small code snippets ✅ Practicing JavaScript ✅ Debugging quickly ✅ Experimenting with logic</p>
<hr />
<h1>REPL Flow</h1>
<pre><code class="language-id=&quot;jlwm212&quot;">Write Code
     ↓
Node Executes
     ↓
Result Printed
     ↓
Wait for Next Input
</code></pre>
<hr />
<h1>Step 4: Create Your First JavaScript File</h1>
<p>Create a folder for your project.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;jlwm213&quot;">my-first-node-app
</code></pre>
<p>Inside it, create a file:</p>
<pre><code class="language-id=&quot;jlwm214&quot;">app.js
</code></pre>
<hr />
<h1>Write Your First Node.js Code</h1>
<p>Inside <code>app.js</code>:</p>
<pre><code class="language-javascript">console.log("Hello Node.js");
</code></pre>
<p>This is your first Node.js program.</p>
<hr />
<h1>Step 5: Run the Script Using Node</h1>
<p>Open terminal inside the project folder.</p>
<p>Run:</p>
<pre><code class="language-bash">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;分快三217&quot;">Hello Node.js
</code></pre>
<p>Congratulations 🎉</p>
<p>You just executed your first Node.js application.</p>
<hr />
<h1>Node Execution Flow</h1>
<pre><code class="language-id=&quot;分快三218&quot;">app.js
   ↓
Node Runtime
   ↓
JavaScript Executes
   ↓
Output Printed in Terminal
</code></pre>
<hr />
<h1>Understanding What Happened</h1>
<p>When you run:</p>
<pre><code class="language-bash">node app.js
</code></pre>
<p>Node.js:</p>
<ol>
<li><p>Reads the file</p>
</li>
<li><p>Executes JavaScript code</p>
</li>
<li><p>Prints output to terminal</p>
</li>
</ol>
<p>Simple but powerful.</p>
<hr />
<h1>Step 6: Writing Your First Hello World Server</h1>
<p>Now let’s create a basic web server.</p>
<p>Replace the code inside <code>app.js</code> with:</p>
<pre><code class="language-javascript">const http = require("http");

const server = http.createServer((req, res) =&gt; {
  res.end("Hello World");
});

server.listen(3000, () =&gt; {
  console.log("Server running on port 3000");
});
</code></pre>
<hr />
<h1>Understanding the Code</h1>
<h3>Import HTTP Module</h3>
<pre><code class="language-javascript">const http = require("http");
</code></pre>
<p>Node.js has a built-in HTTP module for creating servers.</p>
<hr />
<h3>Create Server</h3>
<pre><code class="language-javascript">http.createServer()
</code></pre>
<p>creates a server.</p>
<hr />
<h3>Handle Request and Response</h3>
<pre><code class="language-javascript">(req, res)
</code></pre>
<ul>
<li><p><code>req</code> → incoming request</p>
</li>
<li><p><code>res</code> → server response</p>
</li>
</ul>
<hr />
<h3>Send Response</h3>
<pre><code class="language-javascript">res.end("Hello World");
</code></pre>
<p>sends data back to the browser.</p>
<hr />
<h3>Start Server</h3>
<pre><code class="language-javascript">server.listen(3000)
</code></pre>
<p>starts the server on port 3000.</p>
<hr />
<h1>Run the Server</h1>
<p>In terminal:</p>
<pre><code class="language-bash">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;分快三227&quot;">Server running on port 3000
</code></pre>
<p>Now open browser:</p>
<pre><code class="language-id=&quot;分快三228&quot;">http://localhost:3000
</code></pre>
<p>You’ll see:</p>
<pre><code class="language-id=&quot;分快三229&quot;">Hello World
</code></pre>
<p>Your first Node.js server is now running.</p>
<hr />
<h1>Server Request Flow</h1>
<pre><code class="language-id=&quot;分快三230&quot;">Browser Request
      ↓
Node Server Receives Request
      ↓
Server Sends Response
      ↓
Browser Displays Result
</code></pre>
<hr />
<h1>Why This Is Important</h1>
<p>This small server is the foundation of backend development.</p>
<p>Every backend application works similarly:</p>
<ul>
<li><p>Client sends request</p>
</li>
<li><p>Server processes request</p>
</li>
<li><p>Server sends response</p>
</li>
</ul>
<hr />
<h1>Common Beginner Mistakes</h1>
<h3>Forgetting to Save File</h3>
<p>Always save changes before running.</p>
<hr />
<h3>Wrong File Name</h3>
<p>Make sure:</p>
<pre><code class="language-bash">node app.js
</code></pre>
<p>matches your actual filename.</p>
<hr />
<h3>Port Already in Use</h3>
<p>If port 3000 is busy, try another port:</p>
<pre><code class="language-javascript">server.listen(5000)
</code></pre>
<hr />
<h1>Practice Assignment</h1>
<p>Try these exercises yourself.</p>
<hr />
<h1>1. Install Node.js</h1>
<p>Verify installation using:</p>
<pre><code class="language-bash">node -v
npm -v
</code></pre>
<hr />
<h1>2. Use REPL</h1>
<p>Run:</p>
<pre><code class="language-bash">node
</code></pre>
<p>Try:</p>
<pre><code class="language-javascript">10 + 20
"Hello".toUpperCase()
</code></pre>
<hr />
<h1>3. Create Your Own JS File</h1>
<p>Create:</p>
<pre><code class="language-id=&quot;分快三236&quot;">test.js
</code></pre>
<p>Print:</p>
<pre><code class="language-javascript">console.log("Learning Node.js");
</code></pre>
<p>Run it using:</p>
<pre><code class="language-bash">node test.js
</code></pre>
<hr />
<h1>4. Modify the Server Response</h1>
<p>Change:</p>
<pre><code class="language-javascript">res.end("Hello World");
</code></pre>
<p>to something custom.</p>
<p>Example:</p>
<pre><code class="language-javascript">res.end("Welcome to Node.js");
</code></pre>
<hr />
<h1>Final Thoughts</h1>
<p>Setting up your first Node.js application is the beginning of backend development.</p>
<p>In this article, you learned:</p>
<ul>
<li><p>How to install Node.js</p>
</li>
<li><p>How to verify installation</p>
</li>
<li><p>What REPL is</p>
</li>
<li><p>How to run JavaScript files</p>
</li>
<li><p>How to create a simple server</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;分快三241&quot;">Node.js allows JavaScript to run outside the browser.
</code></pre>
<p>This opens the door to building:</p>
<ul>
<li><p>APIs</p>
</li>
<li><p>Backend servers</p>
</li>
<li><p>Real-time applications</p>
</li>
<li><p>Full-stack projects</p>
</li>
</ul>
<p>Once you are comfortable with basic Node.js setup, you can move toward:</p>
<ul>
<li><p>Express.js</p>
</li>
<li><p>Databases</p>
</li>
<li><p>Authentication</p>
</li>
<li><p>REST APIs</p>
</li>
</ul>
<p>and real-world backend systems.</p>
<hr />
<p>And now, you know how to set up your first Node.js application step-by-step.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[How Node.js Handles Multiple Requests with a Single Thread]]></title><description><![CDATA[One of the most interesting things about Node.js is this:
Node.js is single-threaded

Yet it can still handle thousands of requests efficiently.
This surprises many beginners.
Questions often arise li]]></description><link>https://blogs.abhishekdogra.in/how-node-js-handles-multiple-requests-with-a-single-thread</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/how-node-js-handles-multiple-requests-with-a-single-thread</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:28:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/d2f1fcf6-8e9e-42ab-8aab-e5e7b53c9843.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most interesting things about Node.js is this:</p>
<pre><code class="language-id=&quot;jlwm100&quot;">Node.js is single-threaded
</code></pre>
<p>Yet it can still handle thousands of requests efficiently.</p>
<p>This surprises many beginners.</p>
<p>Questions often arise like:</p>
<ul>
<li><p>If Node.js uses one thread, how does it handle many users?</p>
</li>
<li><p>Why doesn’t the server get blocked?</p>
</li>
<li><p>How can one thread manage so many tasks?</p>
</li>
</ul>
<p>In this article, we’ll understand:</p>
<ul>
<li><p>The single-threaded nature of Node.js</p>
</li>
<li><p>The role of the event loop</p>
</li>
<li><p>How background workers help</p>
</li>
<li><p>How Node.js handles multiple requests</p>
</li>
<li><p>Why Node.js scales so well</p>
</li>
</ul>
<p>Let’s start with the basics.</p>
<hr />
<h2>What Is a Thread?</h2>
<p>A thread is the smallest unit of execution inside a program.</p>
<p>Think of a thread as:</p>
<pre><code class="language-id=&quot;jlwm101&quot;">A worker performing tasks
</code></pre>
<p>Traditional backend systems often create:</p>
<ul>
<li><p>one thread per request</p>
</li>
<li><p>multiple threads for concurrency</p>
</li>
</ul>
<p>But Node.js works differently.</p>
<hr />
<h2>Node.js Is Single-Threaded</h2>
<p>Node.js mainly uses:</p>
<pre><code class="language-id=&quot;jlwm102&quot;">One main thread
</code></pre>
<p>This thread handles:</p>
<ul>
<li><p>receiving requests</p>
</li>
<li><p>executing JavaScript code</p>
</li>
<li><p>managing callbacks</p>
</li>
<li><p>running the event loop</p>
</li>
</ul>
<p>At first, this sounds limiting.</p>
<p>But Node.js uses a smart architecture to avoid blocking.</p>
<hr />
<h2>Chef Handling Orders Analogy</h2>
<p>Imagine a restaurant chef.</p>
<p>The chef:</p>
<ul>
<li><p>takes orders</p>
</li>
<li><p>sends cooking tasks to helpers</p>
</li>
<li><p>continues handling other customers</p>
</li>
</ul>
<p>The chef does not personally cook everything alone.</p>
<p>Similarly:</p>
<pre><code class="language-id=&quot;jlwm103&quot;">Node.js = Chef
Background workers = Kitchen helpers
</code></pre>
<p>Node.js delegates heavy tasks and continues handling new requests.</p>
<hr />
<h2>Understanding Concurrency vs Parallelism</h2>
<p>This is extremely important.</p>
<h3>Concurrency</h3>
<pre><code class="language-id=&quot;jlwm104&quot;">Handling multiple tasks efficiently
</code></pre>
<h3>Parallelism</h3>
<pre><code class="language-id=&quot;jlwm105&quot;">Running multiple tasks at the exact same time
</code></pre>
<p>Node.js mainly focuses on:</p>
<pre><code class="language-id=&quot;jlwm106&quot;">Concurrency
</code></pre>
<p>not true parallel execution of JavaScript code.</p>
<hr />
<h2>Handling Multiple Requests</h2>
<p>Suppose 3 users send requests simultaneously.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;jlwm107&quot;">User A → Request
User B → Request
User C → Request
</code></pre>
<p>Node.js handles them without creating one thread per request.</p>
<p>Instead:</p>
<pre><code class="language-id=&quot;jlwm108&quot;">Event Loop manages request flow
</code></pre>
<hr />
<h2>What Is the Event Loop?</h2>
<p>The event loop is the heart of Node.js concurrency.</p>
<p>Its job is to:</p>
<ul>
<li><p>monitor tasks</p>
</li>
<li><p>check completed operations</p>
</li>
<li><p>execute callbacks when tasks finish</p>
</li>
</ul>
<p>The event loop continuously runs in a cycle.</p>
<hr />
<h2>Event Loop Flow</h2>
<pre><code class="language-id=&quot;jlwm109&quot;">Receive Request
       ↓
Start Async Task
       ↓
Continue Handling Other Requests
       ↓
Task Completes
       ↓
Callback Added to Queue
       ↓
Event Loop Executes Callback
</code></pre>
<p>This allows Node.js to stay fast and responsive.</p>
<hr />
<h2>Example with File Reading</h2>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

console.log("Start");

fs.readFile("demo.txt", "utf8", (err, data) =&gt; {
  console.log(data);
});

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm111&quot;">Start
End
File Content
</code></pre>
<p>Notice:</p>
<ul>
<li><p>Node.js does not wait for file reading</p>
</li>
<li><p>It continues executing other code</p>
</li>
<li><p>Callback runs later</p>
</li>
</ul>
<p>This is asynchronous behavior.</p>
<hr />
<h2>How Background Workers Help</h2>
<p>Some operations are slow.</p>
<p>Examples:</p>
<ul>
<li><p>File system operations</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>Network requests</p>
</li>
<li><p>Cryptographic tasks</p>
</li>
</ul>
<p>Node.js delegates these tasks to:</p>
<pre><code class="language-id=&quot;jlwm112&quot;">Background worker threads
</code></pre>
<p>managed internally by:</p>
<pre><code class="language-id=&quot;jlwm113&quot;">libuv
</code></pre>
<hr />
<h2>Event Loop + Worker Thread Flow</h2>
<pre><code class="language-id=&quot;jlwm114&quot;">Main Thread
     ↓
Receives Request
     ↓
Delegates Heavy Task
     ↓
Worker Handles Task
     ↓
Task Completes
     ↓
Callback Sent Back
     ↓
Event Loop Executes Callback
</code></pre>
<p>This is how Node.js avoids blocking.</p>
<hr />
<h2>Why the Main Thread Stays Free</h2>
<p>The main thread only manages:</p>
<ul>
<li><p>callbacks</p>
</li>
<li><p>events</p>
</li>
<li><p>request coordination</p>
</li>
</ul>
<p>Heavy operations happen elsewhere.</p>
<p>So while one task is waiting:</p>
<pre><code class="language-id=&quot;jlwm115&quot;">Node.js continues serving other users
</code></pre>
<hr />
<h2>Single Thread Handling Multiple Requests</h2>
<pre><code class="language-id=&quot;jlwm116&quot;">Request 1 ─┐
Request 2 ─┼──→ Event Loop
Request 3 ─┘
                 ↓
        Async Tasks Delegated
                 ↓
         Callbacks Executed Later
</code></pre>
<p>This architecture is very efficient for I/O-heavy applications.</p>
<hr />
<h2>Why Node.js Scales Well</h2>
<p>Node.js scales well because:</p>
<p>✅ Very little thread overhead ✅ Non-blocking architecture ✅ Fast request handling ✅ Efficient memory usage ✅ Event-driven design</p>
<p>Instead of creating thousands of threads:</p>
<pre><code class="language-id=&quot;jlwm117&quot;">One event loop manages many requests
</code></pre>
<hr />
<h2>Real-World Example</h2>
<p>Imagine an API server.</p>
<p>Users are:</p>
<ul>
<li><p>logging in</p>
</li>
<li><p>fetching products</p>
</li>
<li><p>uploading images</p>
</li>
<li><p>reading data</p>
</li>
</ul>
<p>Most tasks involve waiting:</p>
<ul>
<li><p>database responses</p>
</li>
<li><p>network operations</p>
</li>
<li><p>file system operations</p>
</li>
</ul>
<p>Node.js uses this waiting time efficiently instead of blocking the thread.</p>
<hr />
<h2>Blocking vs Non-Blocking Behavior</h2>
<h3>Blocking Example</h3>
<pre><code class="language-id=&quot;jlwm118&quot;">Wait for Task
      ↓
Everything Stops
</code></pre>
<hr />
<h3>Non-Blocking Example</h3>
<pre><code class="language-id=&quot;jlwm119&quot;">Start Task
      ↓
Continue Other Work
      ↓
Handle Result Later
</code></pre>
<p>Node.js heavily relies on non-blocking operations.</p>
<hr />
<h2>Does Node.js Use Only One Thread?</h2>
<p>This is a common misconception.</p>
<p>JavaScript execution mainly runs on one thread.</p>
<p>But internally:</p>
<ul>
<li><p>worker threads exist</p>
</li>
<li><p>background threads exist</p>
</li>
<li><p>system-level threads exist</p>
</li>
</ul>
<p>Still, developers mostly interact with:</p>
<pre><code class="language-id=&quot;jlwm120&quot;">A single JavaScript thread
</code></pre>
<hr />
<h2>Best Use Cases for Node.js</h2>
<p>Node.js performs extremely well for:</p>
<p>✅ APIs ✅ Real-time apps ✅ Chat applications ✅ Streaming services ✅ Microservices</p>
<p>because these applications are heavily I/O-based.</p>
<hr />
<h2>When Node.js Can Struggle</h2>
<p>CPU-heavy tasks can block the event loop.</p>
<p>Examples:</p>
<ul>
<li><p>image processing</p>
</li>
<li><p>video rendering</p>
</li>
<li><p>heavy calculations</p>
</li>
</ul>
<p>If one CPU-intensive task blocks the main thread:</p>
<pre><code class="language-id=&quot;jlwm121&quot;">All requests slow down
</code></pre>
<p>This is why worker threads or separate services are sometimes used.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Observe Async Behavior</h2>
<p>Use:</p>
<pre><code class="language-javascript">setTimeout()
</code></pre>
<p>and multiple <code>console.log()</code> statements.</p>
<p>Observe execution order.</p>
<hr />
<h2>2. Try File Reading</h2>
<p>Use:</p>
<pre><code class="language-javascript">fs.readFile()
</code></pre>
<p>and notice how Node.js continues executing code.</p>
<hr />
<h2>3. Understand Event Loop Thinking</h2>
<p>Ask yourself:</p>
<pre><code class="language-id=&quot;jlwm124&quot;">Why doesn't Node.js wait for slow tasks?
</code></pre>
<p>This question helps build async understanding.</p>
<hr />
<h2>4. Compare with Real Life</h2>
<p>Think about:</p>
<ul>
<li><p>restaurant chefs</p>
</li>
<li><p>delivery systems</p>
</li>
<li><p>customer service queues</p>
</li>
</ul>
<p>These analogies help understand concurrency.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Node.js achieves high scalability using:</p>
<ul>
<li><p>a single JavaScript thread</p>
</li>
<li><p>asynchronous programming</p>
</li>
<li><p>the event loop</p>
</li>
<li><p>background workers</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;jlwm125&quot;">Node.js does not do everything itself.
It delegates slow tasks and keeps moving.
</code></pre>
<p>This architecture allows Node.js to efficiently handle thousands of concurrent requests without creating massive numbers of threads.</p>
<p>Understanding:</p>
<ul>
<li><p>the event loop</p>
</li>
<li><p>async behavior</p>
</li>
<li><p>concurrency</p>
</li>
</ul>
<p>is one of the most important steps toward becoming a strong backend developer.</p>
<hr />
<p>And now, you know how Node.js handles multiple requests with a single thread.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[The new Keyword in JavaScript
]]></title><description><![CDATA[In JavaScript, objects can be created in multiple ways.
One powerful way is to use the:
new

keyword.
The new keyword is commonly used with:

Constructor functions

Classes

Object creation patterns

]]></description><link>https://blogs.abhishekdogra.in/the-new-keyword-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/the-new-keyword-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:24:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/0106dc1e-b8f0-4c77-a5dd-f1bb17349073.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In JavaScript, objects can be created in multiple ways.</p>
<p>One powerful way is to use the:</p>
<pre><code class="language-javascript">new
</code></pre>
<p>keyword.</p>
<p>The <code>new</code> keyword is commonly used with:</p>
<ul>
<li><p>Constructor functions</p>
</li>
<li><p>Classes</p>
</li>
<li><p>Object creation patterns</p>
</li>
</ul>
<p>Understanding how <code>new</code> Works helps you understand the foundation of object-oriented programming in JavaScript.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What the <code>new</code> keyword does</p>
</li>
<li><p>Constructor functions</p>
</li>
<li><p>The object creation process</p>
</li>
<li><p>How <code>new</code> links prototypes</p>
</li>
<li><p>Instances created from constructors</p>
</li>
</ul>
<p>Let’s start with the basics.</p>
<hr />
<h2>What Does the <code>new</code> Keyword Do?</h2>
<p>The <code>new</code> keyword creates a new object from a constructor function.</p>
<p>Example:</p>
<pre><code class="language-javascript">function Person(name) {
  this.name = name;
}

const user1 = new Person("Rahul");

console.log(user1);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{ name: "Rahul" }
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>new</code> creates a brand-new object</p>
</li>
<li><p>The object gets linked to the constructor</p>
</li>
<li><p><code>this</code> points to the new object</p>
</li>
</ul>
<hr />
<h2>What Is a Constructor Function?</h2>
<p>A constructor function is a normal function used to create objects.</p>
<p>By convention, constructor names start with a capital letter.</p>
<p>Example:</p>
<pre><code class="language-javascript">function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}
</code></pre>
<p>This function acts like a blueprint for creating car objects.</p>
<hr />
<h2>Creating Objects Without <code>new</code></h2>
<p>Example:</p>
<pre><code class="language-javascript">function Person(name) {
  this.name = name;
}

const user = Person("Rahul");

console.log(user);
</code></pre>
<p>This does not work properly because:</p>
<pre><code class="language-id=&quot;jlwm06&quot;">No new object was created
</code></pre>
<p>The <code>new</code> keyword is what makes constructor functions behave correctly.</p>
<hr />
<h2>Creating Objects Using <code>new</code></h2>
<p>Example:</p>
<pre><code class="language-javascript">function Person(name, age) {
  this.name = name;
  this.age = age;
}

const user1 = new Person("Rahul", 22);

console.log(user1);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{
  name: "Rahul",
  age: 22
}
</code></pre>
<hr />
<h2>Step-by-Step Object Creation Process</h2>
<p>When JavaScript sees:</p>
<pre><code class="language-javascript">new Person("Rahul")
</code></pre>
<p>it performs several steps automatically.</p>
<hr />
<h2>Step 1: Create a New Empty Object</h2>
<p>JavaScript internally creates:</p>
<pre><code class="language-javascript">{}
</code></pre>
<hr />
<h2>Step 2: Link the Object to Prototype</h2>
<p>The object is connected to:</p>
<pre><code class="language-javascript">Person.prototype
</code></pre>
<p>This allows the object to access shared methods.</p>
<hr />
<h2>Step 3: <code>this</code> Points to the New Object</h2>
<p>Inside the constructor:</p>
<pre><code class="language-javascript">this.name = name;
</code></pre>
<p><code>this</code> refers to the newly created object.</p>
<hr />
<h2>Step 4: Return the Object</h2>
<p>JavaScript automatically returns the new object.</p>
<p>Final result:</p>
<pre><code class="language-javascript">{
  name: "Rahul"
}
</code></pre>
<hr />
<h2>Object Creation Flow</h2>
<pre><code class="language-id=&quot;jlwm14&quot;">new Person()
      ↓
Create Empty Object
      ↓
Link Prototype
      ↓
Bind this
      ↓
Return Object
</code></pre>
<p>This is what the <code>new</code> keyword does internally.</p>
<hr />
<h2>Instances Created from Constructors</h2>
<p>Objects created using constructor functions are called:</p>
<pre><code class="language-id=&quot;jlwm15&quot;">Instances
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">function Student(name) {
  this.name = name;
}

const s1 = new Student("Rahul");
const s2 = new Student("Aman");
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>s1</code> is an instance of <code>Student</code></p>
</li>
<li><p><code>s2</code> is another instance of <code>Student</code></p>
</li>
</ul>
<hr />
<h2>Constructor → Instance Relationship</h2>
<pre><code class="language-id=&quot;jlwm17&quot;">Constructor Function
        ↓
Creates
        ↓
Object Instances
</code></pre>
<p>Example:</p>
<pre><code class="language-id=&quot;jlwm18&quot;">Student()
   ↓
s1
s2
s3
</code></pre>
<p>One constructor can create many objects.</p>
<hr />
<h2>Adding Methods to Constructor Functions</h2>
<p>Example:</p>
<pre><code class="language-javascript">function Person(name) {
  this.name = name;

  this.greet = function() {
    console.log("Hello " + this.name);
  };
}

const user = new Person("Rahul");

user.greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm20&quot;">Hello Rahul
</code></pre>
<p>The created object now has properties and methods.</p>
<hr />
<h2>How <code>new</code> Links Prototypes</h2>
<p>Every constructor function has a:</p>
<pre><code class="language-javascript">prototype
</code></pre>
<p>property.</p>
<p>Objects created with <code>new</code> are linked to that prototype.</p>
<p>Example:</p>
<pre><code class="language-javascript">function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log("Hello");
};

const user = new Person("Rahul");

user.sayHello();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm23&quot;">Hello
</code></pre>
<p>Even though <code>sayHello()</code> is not directly inside the object, it works because of prototype linking.</p>
<hr />
<h2>Prototype Linking Visualization</h2>
<pre><code class="language-id=&quot;jlwm24&quot;">user object
    ↓
linked to
    ↓
Person.prototype
</code></pre>
<p>This is one of JavaScript’s core concepts.</p>
<hr />
<h2>Why Prototypes Are Useful</h2>
<p>If methods are added inside the constructor:</p>
<pre><code class="language-javascript">this.greet = function(){}
</code></pre>
<p>every object gets its own copy.</p>
<p>But with prototypes:</p>
<pre><code class="language-javascript">Person.prototype.greet = function(){}
</code></pre>
<p>all objects share the same method.</p>
<p>This improves memory efficiency.</p>
<hr />
<h2>Real-World Example</h2>
<p>Imagine a blueprint for cars.</p>
<pre><code class="language-id=&quot;jlwm27&quot;">Car Blueprint
     ↓
Creates
     ↓
Many Car Objects
</code></pre>
<p>Each car:</p>
<ul>
<li><p>has its own data</p>
</li>
<li><p>shares common behavior</p>
</li>
</ul>
<p>Constructor functions work similarly.</p>
<hr />
<h2>Checking Instances</h2>
<p>JavaScript provides:</p>
<pre><code class="language-javascript">instanceof
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">console.log(user instanceof Person);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm30&quot;">true
</code></pre>
<p>This confirms the object was created using that constructor.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Create a Constructor Function</h2>
<p>Create a constructor called:</p>
<pre><code class="language-id=&quot;jlwm31&quot;">Book
</code></pre>
<p>Add:</p>
<ul>
<li><p>title</p>
</li>
<li><p>author</p>
</li>
</ul>
<hr />
<h2>2. Create Multiple Instances</h2>
<p>Example:</p>
<pre><code class="language-javascript">const b1 = new Book(...);
const b2 = new Book(...);
</code></pre>
<hr />
<h2>3. Add a Prototype Method</h2>
<p>Add:</p>
<pre><code class="language-javascript">Book.prototype.getDetails
</code></pre>
<p>and print book information.</p>
<hr />
<h2>4. Use <code>instanceof</code></h2>
<p>Check whether objects belong to the constructor.</p>
<hr />
<h2>Final Thoughts</h2>
<p>The <code>new</code> keyword is one of JavaScript’s most important object creation features.</p>
<p>It helps JavaScript:</p>
<ul>
<li><p>Create new objects</p>
</li>
<li><p>Bind <code>this</code> correctly</p>
</li>
<li><p>Connect objects to prototypes</p>
</li>
<li><p>Build reusable object structures</p>
</li>
</ul>
<p>The key idea is:</p>
<pre><code class="language-id=&quot;jlwm34&quot;">Constructor function = blueprint
Objects = instances created from that blueprint
</code></pre>
<p>Understanding <code>new</code> and constructor functions builds the foundation for learning:</p>
<ul>
<li><p>Prototypes</p>
</li>
<li><p>Classes</p>
</li>
<li><p>Inheritance</p>
</li>
<li><p>Object-oriented programming</p>
</li>
</ul>
<p>Mastering these concepts will make advanced JavaScript much easier to understand.</p>
<hr />
<p>And now, you know what the <code>new</code> keyword in JavaScript is.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Callbacks in JavaScript: Why They Exist]]></title><description><![CDATA[JavaScript is a language where functions are extremely powerful.
In JavaScript:

Functions can be stored in variables

Functions can be passed as arguments

Functions can be returned from other functi]]></description><link>https://blogs.abhishekdogra.in/callbacks-in-javascript-why-they-exist</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/callbacks-in-javascript-why-they-exist</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:12:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/78e26430-c122-4880-ae33-38b7b38040a0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript is a language where functions are extremely powerful.</p>
<p>In JavaScript:</p>
<ul>
<li><p>Functions can be stored in variables</p>
</li>
<li><p>Functions can be passed as arguments</p>
</li>
<li><p>Functions can be returned from other functions</p>
</li>
</ul>
<p>This flexibility allows us to use something called <strong>callbacks</strong>.</p>
<p>Callbacks are one of the most important concepts in JavaScript, especially in asynchronous programming.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What a callback function is</p>
</li>
<li><p>Why callbacks are used</p>
</li>
<li><p>Passing functions as arguments</p>
</li>
<li><p>Real-world callback usage</p>
</li>
<li><p>Problems with nested callbacks</p>
</li>
</ul>
<p>Let’s begin with the basics.</p>
<hr />
<h2>Functions as Values in JavaScript</h2>
<p>In JavaScript, functions behave like normal values.</p>
<p>We can store them inside variables.</p>
<p>Example:</p>
<pre><code class="language-javascript">const greet = function() {
  console.log("Hello");
};

greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;mjlwm2&quot;">Hello
</code></pre>
<p>Since functions are values, we can also pass them into other functions.</p>
<p>This is where callbacks begin.</p>
<hr />
<h2>What Is a Callback Function?</h2>
<p>A callback is simply:</p>
<pre><code class="language-id=&quot;tjlwm4&quot;">A function passed into another function
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">function greet(name, callback) {
  console.log("Hello " + name);

  callback();
}

function sayBye() {
  console.log("Goodbye");
}

greet("Rahul", sayBye);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;6jlwm0&quot;">Hello Rahul
Goodbye
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>sayBye</code> is passed as an argument</p>
</li>
<li><p><code>sayBye</code> is the callback function</p>
</li>
</ul>
<hr />
<h2>Understanding the Flow</h2>
<pre><code class="language-id=&quot;9jlwm1&quot;">greet()
   ↓
Print greeting
   ↓
Execute callback()
</code></pre>
<p>The callback runs after the main task completes.</p>
<hr />
<h2>Why Do Callbacks Exist?</h2>
<p>Callbacks exist because sometimes we want code to run:</p>
<p>✅ Later<br />✅ After another task finishes<br />✅ Only when something happens</p>
<p>Examples include:</p>
<ul>
<li><p>Reading files</p>
</li>
<li><p>API requests</p>
</li>
<li><p>Button clicks</p>
</li>
<li><p>Timers</p>
</li>
</ul>
<p>Callbacks allow JavaScript to handle these situations.</p>
<hr />
<h2>Passing Functions as Arguments</h2>
<p>Let’s look at another simple example.</p>
<p>Example:</p>
<pre><code class="language-javascript">function calculate(a, b, operation) {
  return operation(a, b);
}

function add(x, y) {
  return x + y;
}

console.log(calculate(2, 3, add));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;jlwm49&quot;">5
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>add</code> is passed as an argument</p>
</li>
<li><p><code>calculate</code> executes the callback function</p>
</li>
</ul>
<p>This makes code more flexible and reusable.</p>
<hr />
<h2>Real-World Callback Example</h2>
<p>Imagine ordering food online.</p>
<p>Flow:</p>
<pre><code class="language-id=&quot;8jlwm7&quot;">Place Order
    ↓
Wait for Food
    ↓
Food Delivered
    ↓
Receive Notification
</code></pre>
<p>The notification happens only after delivery finishes.</p>
<p>Callbacks work similarly in programming.</p>
<hr />
<h2>Callback Example with <code>setTimeout</code></h2>
<p>Example:</p>
<pre><code class="language-javascript">console.log("Start");

setTimeout(() =&gt; {
  console.log("Task Completed");
}, 2000);

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;7jlwm2&quot;">Start
End
Task Completed
</code></pre>
<hr />
<h2>What Happened Here?</h2>
<pre><code class="language-id=&quot;qjlwm8&quot;">Start runs first
      ↓
Timer starts
      ↓
JS continues execution
      ↓
End prints
      ↓
After 2 seconds callback executes
</code></pre>
<p>This is asynchronous behavior.</p>
<hr />
<h2>Why Callbacks Are Important in Async Programming</h2>
<p>Some operations take time.</p>
<p>Examples:</p>
<ul>
<li><p>Fetching data from servers</p>
</li>
<li><p>Reading files</p>
</li>
<li><p>Database queries</p>
</li>
</ul>
<p>JavaScript does not want to stop the entire program while waiting.</p>
<p>Instead:</p>
<pre><code class="language-id=&quot;yjlwm4&quot;">Start task
Continue other work
Run callback when task finishes
</code></pre>
<p>This makes applications faster and responsive.</p>
<hr />
<h2>Callback Usage in Common Scenarios</h2>
<p>Callbacks are used in many places.</p>
<hr />
<h2>Event Handling</h2>
<p>Example:</p>
<pre><code class="language-javascript">button.addEventListener("click", function() {
  console.log("Button clicked");
});
</code></pre>
<p>The callback runs only when the button is clicked.</p>
<hr />
<h2>Timers</h2>
<p>Example:</p>
<pre><code class="language-javascript">setTimeout(() =&gt; {
  console.log("Hello after 2 seconds");
}, 2000);
</code></pre>
<hr />
<h2>Array Methods</h2>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3];

numbers.forEach(function(num) {
  console.log(num);
});
</code></pre>
<p>The function inside <code>forEach()</code> is also a callback.</p>
<hr />
<h2>Callback Flow Diagram</h2>
<pre><code class="language-id=&quot;jlwm14&quot;">Main Function
      ↓
Receives Callback
      ↓
Performs Task
      ↓
Executes Callback
</code></pre>
<hr />
<h2>The Problem with Nested Callbacks</h2>
<p>Callbacks are useful, but deeply nested callbacks can become difficult to read.</p>
<p>Example:</p>
<pre><code class="language-javascript">loginUser(function(user) {
  getPosts(user, function(posts) {
    getComments(posts, function(comments) {
      console.log(comments);
    });
  });
});
</code></pre>
<p>This structure becomes messy quickly.</p>
<hr />
<h2>Callback Nesting Visualization</h2>
<pre><code class="language-id=&quot;jlwm57&quot;">Task 1
  ↓
Task 2
   ↓
Task 3
    ↓
Task 4
</code></pre>
<p>As nesting increases:</p>
<ul>
<li><p>Code becomes harder to read</p>
</li>
<li><p>Debugging becomes difficult</p>
</li>
<li><p>Maintenance becomes harder</p>
</li>
</ul>
<p>This problem is commonly called:</p>
<pre><code class="language-id=&quot;jlwm88&quot;">Callback Hell
</code></pre>
<hr />
<h2>Why Callback Hell Is Problematic</h2>
<p>Problems include:</p>
<p>❌ Deep nesting<br />❌ Poor readability<br />❌ Hard debugging<br />❌ Difficult maintenance</p>
<p>This is one reason Promises and async/await were introduced later.</p>
<hr />
<h2>Simple Callback vs Nested Callback</h2>
<h3>Simple Callback</h3>
<pre><code class="language-javascript">sayHello(callback);
</code></pre>
<p>Easy to understand.</p>
<hr />
<h3>Nested Callback</h3>
<pre><code class="language-javascript">task1(() =&gt; {
  task2(() =&gt; {
    task3(() =&gt; {
      task4(() =&gt; {});
    });
  });
});
</code></pre>
<p>Much harder to manage.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Create a Callback Function</h2>
<p>Write a function that:</p>
<ul>
<li><p>prints a message</p>
</li>
<li><p>executes a callback afterward</p>
</li>
</ul>
<hr />
<h2>2. Use <code>setTimeout</code></h2>
<p>Create a timer that prints:</p>
<pre><code class="language-id=&quot;jlwm66&quot;">"Task Finished"
</code></pre>
<p>after 3 seconds.</p>
<hr />
<h2>3. Use a Callback with Arrays</h2>
<p>Use:</p>
<pre><code class="language-javascript">forEach()
</code></pre>
<p>to print array elements.</p>
<hr />
<h2>4. Observe Callback Flow</h2>
<p>Try adding multiple <code>console.log()</code> statements to understand execution order.</p>
<p>This helps build asynchronous thinking.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Callbacks are one of the foundations of JavaScript.</p>
<p>They allow JavaScript to:</p>
<ul>
<li><p>Handle asynchronous tasks</p>
</li>
<li><p>Execute code later</p>
</li>
<li><p>Respond to events</p>
</li>
<li><p>Build dynamic applications</p>
</li>
</ul>
<p>The key idea is simple:</p>
<pre><code class="language-id=&quot;jlwm44&quot;">A callback is a function passed into another function to run later.
</code></pre>
<p>Although nested callbacks can become messy, understanding callbacks is extremely important because they form the foundation for:</p>
<ul>
<li><p>Promises</p>
</li>
<li><p>async/await</p>
</li>
<li><p>Event-driven programming</p>
</li>
</ul>
<p>Mastering callbacks will make learning modern asynchronous JavaScript much easier.</p>
<hr />
<p>And now, you know what Callbacks in JavaScript are and why they exist.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[URL Parameters vs Query Strings in Express.js]]></title><description><![CDATA[When building APIs in Express.js, we often need to send data through URLs.
For example:

Fetching a specific user profile

Searching products

Filtering results

Pagination


This is where:

URL Param]]></description><link>https://blogs.abhishekdogra.in/url-parameters-vs-query-strings-in-express-js</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/url-parameters-vs-query-strings-in-express-js</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:11:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/758faccb-6716-491d-8fd4-e16f7761e276.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building APIs in Express.js, we often need to send data through URLs.</p>
<p>For example:</p>
<ul>
<li><p>Fetching a specific user profile</p>
</li>
<li><p>Searching products</p>
</li>
<li><p>Filtering results</p>
</li>
<li><p>Pagination</p>
</li>
</ul>
<p>This is where:</p>
<ul>
<li><p>URL Parameters</p>
</li>
<li><p>Query Strings</p>
</li>
</ul>
<p>become very important.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What URL parameters are</p>
</li>
<li><p>What query parameters are</p>
</li>
<li><p>Differences between them</p>
</li>
<li><p>How to access them in Express</p>
</li>
<li><p>When to use params vs query strings</p>
</li>
</ul>
<p>Let’s begin with the basics.</p>
<hr />
<h2>Understanding URL Structure</h2>
<p>Example URL:</p>
<pre><code class="language-id=&quot;h2u0f7&quot;">http://localhost:3000/users/101?active=true
</code></pre>
<p>This URL contains both:</p>
<ul>
<li><p>URL parameter</p>
</li>
<li><p>Query parameter</p>
</li>
</ul>
<p>Breakdown:</p>
<pre><code class="language-id=&quot;n0qjlwm&quot;">/users/101
        ↑
    URL Parameter

?active=true
       ↑
   Query Parameter
</code></pre>
<hr />
<h2>What Are URL Parameters?</h2>
<p>URL parameters are values placed directly inside the URL path.</p>
<p>They usually identify a specific resource.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;epjlwm&quot;">/users/101
</code></pre>
<p>Here:</p>
<pre><code class="language-id=&quot;3w4c8v&quot;">101
</code></pre>
<p>is the parameter.</p>
<p>It commonly represents:</p>
<ul>
<li><p>User ID</p>
</li>
<li><p>Product ID</p>
</li>
<li><p>Blog ID</p>
</li>
</ul>
<p>Think of params as:</p>
<pre><code class="language-id=&quot;4v8fqs&quot;">Identifiers
</code></pre>
<hr />
<h2>Real-World Example</h2>
<p>Suppose we want details of a specific user.</p>
<p>URL:</p>
<pre><code class="language-id=&quot;sjlwmx&quot;">/users/101
</code></pre>
<p>Meaning:</p>
<pre><code class="language-id=&quot;8lbmne&quot;">"Fetch user whose ID is 101"
</code></pre>
<p>This uniquely identifies a resource.</p>
<hr />
<h2>Defining URL Params in Express</h2>
<p>Example:</p>
<pre><code class="language-javascript">const express = require("express");

const app = express();

app.get("/users/:id", (req, res) =&gt; {
  res.send(`User ID is ${req.params.id}`);
});

app.listen(3000);
</code></pre>
<hr />
<h2>Accessing Params in Express</h2>
<p>We use:</p>
<pre><code class="language-javascript">req.params
</code></pre>
<p>Example request:</p>
<pre><code class="language-id=&quot;ap53lh&quot;">/users/101
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;s8k3cw&quot;">User ID is 101
</code></pre>
<p>Here:</p>
<pre><code class="language-javascript">req.params.id
</code></pre>
<p>contains:</p>
<pre><code class="language-id=&quot;jlwm9&quot;">101
</code></pre>
<hr />
<h2>Multiple URL Parameters</h2>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/users/:userId/posts/:postId", (req, res) =&gt; {
  res.send(req.params);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-id=&quot;6ec4j0&quot;">/users/10/posts/55
</code></pre>
<p>Result:</p>
<pre><code class="language-javascript">{
  userId: "10",
  postId: "55"
}
</code></pre>
<hr />
<h2>What Are Query Parameters?</h2>
<p>Query parameters are extra information added after <code>?</code> in the URL.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;78u5fa&quot;">/products?category=mobile
</code></pre>
<p>Here:</p>
<pre><code class="language-id=&quot;rjlwmz&quot;">category=mobile
</code></pre>
<p>is a query parameter.</p>
<p>Query strings are usually used for:</p>
<ul>
<li><p>Filters</p>
</li>
<li><p>Search</p>
</li>
<li><p>Sorting</p>
</li>
<li><p>Pagination</p>
</li>
</ul>
<p>Think of query params as:</p>
<pre><code class="language-id=&quot;fjlwm7&quot;">Modifiers or Filters
</code></pre>
<hr />
<h2>Real-World Example</h2>
<p>Suppose we want to search products.</p>
<p>URL:</p>
<pre><code class="language-id=&quot;d9mjlwm&quot;">/products?category=shoes&amp;price=2000
</code></pre>
<p>Meaning:</p>
<pre><code class="language-id=&quot;1l93m8&quot;">"Show shoes with price 2000"
</code></pre>
<p>The resource is still:</p>
<pre><code class="language-id=&quot;7ccz4d&quot;">/products
</code></pre>
<p>but the query changes how results are filtered.</p>
<hr />
<h2>Accessing Query Strings in Express</h2>
<p>We use:</p>
<pre><code class="language-javascript">req.query
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">app.get("/products", (req, res) =&gt; {
  res.send(req.query);
});
</code></pre>
<p>Request:</p>
<pre><code class="language-id=&quot;7jlwm5&quot;">/products?category=mobile&amp;brand=apple
</code></pre>
<p>Result:</p>
<pre><code class="language-javascript">{
  category: "mobile",
  brand: "apple"
}
</code></pre>
<hr />
<h2>Query Parameter Breakdown</h2>
<pre><code class="language-id=&quot;2rfjlwm&quot;">/products?category=mobile&amp;brand=apple

/products
     ↑
 Resource

category=mobile
brand=apple
     ↑
 Query Parameters
</code></pre>
<hr />
<h2>Params vs Query Strings</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>URL Params</th>
<th>Query Strings</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Identify resource</td>
<td>Filter or modify results</td>
</tr>
<tr>
<td>Position</td>
<td>Inside URL path</td>
<td>After <code>?</code></td>
</tr>
<tr>
<td>Example</td>
<td><code>/users/10</code></td>
<td><code>/users?active=true</code></td>
</tr>
<tr>
<td>Accessed Using</td>
<td><code>req.params</code></td>
<td><code>req.query</code></td>
</tr>
<tr>
<td>Common Usage</td>
<td>IDs</td>
<td>Search, filters, sorting</td>
</tr>
</tbody></table>
<hr />
<h2>Simple Comparison</h2>
<h3>URL Parameter Example</h3>
<pre><code class="language-id=&quot;4qjlwm&quot;">/users/25
</code></pre>
<p>Meaning:</p>
<pre><code class="language-id=&quot;8jlwm4&quot;">Get user with ID 25
</code></pre>
<hr />
<h3>Query String Example</h3>
<pre><code class="language-id=&quot;jlwm18&quot;">/users?country=india
</code></pre>
<p>Meaning:</p>
<pre><code class="language-id=&quot;x0k1dp&quot;">Get users filtered by country
</code></pre>
<hr />
<h2>When Should You Use URL Params?</h2>
<p>Use params when:</p>
<p>✅ Identifying a specific resource ✅ Resource is required ✅ URL represents a unique entity</p>
<p>Examples:</p>
<pre><code class="language-id=&quot;mejlwm&quot;">/users/5
/products/10
/posts/100
</code></pre>
<hr />
<h2>When Should You Use Query Strings?</h2>
<p>Use query strings when:</p>
<p>✅ Filtering data ✅ Searching ✅ Sorting ✅ Pagination</p>
<p>Examples:</p>
<pre><code class="language-id=&quot;jlwm31&quot;">/products?category=laptop

/users?page=2

/posts?sort=latest
</code></pre>
<hr />
<h2>Real-World API Examples</h2>
<h3>Fetch Specific Product</h3>
<pre><code class="language-id=&quot;3jlwmv&quot;">/products/101
</code></pre>
<p>Uses URL params.</p>
<hr />
<h3>Search Products</h3>
<pre><code class="language-id=&quot;jlwm67&quot;">/products?category=phone&amp;brand=samsung
</code></pre>
<p>Uses query strings.</p>
<hr />
<h2>Combining Params and Query</h2>
<p>Sometimes both are used together.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;rjlwm8&quot;">/users/10/orders?status=completed
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>10</code> → URL param</p>
</li>
<li><p><code>status=completed</code> → query param</p>
</li>
</ul>
<p>Meaning:</p>
<pre><code class="language-id=&quot;jlwm90&quot;">Get completed orders for user 10
</code></pre>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Create a Route with Params</h2>
<p>Example:</p>
<pre><code class="language-id=&quot;jlwm12&quot;">/students/1
</code></pre>
<p>Return the student ID using:</p>
<pre><code class="language-javascript">req.params
</code></pre>
<hr />
<h2>2. Create a Route with Query Strings</h2>
<p>Example:</p>
<pre><code class="language-id=&quot;jlwm54&quot;">/search?keyword=nodejs
</code></pre>
<p>Return the query value using:</p>
<pre><code class="language-javascript">req.query
</code></pre>
<hr />
<h2>3. Combine Both</h2>
<p>Try:</p>
<pre><code class="language-id=&quot;jlwm65&quot;">/users/5/posts?sort=latest
</code></pre>
<p>Understand:</p>
<ul>
<li><p>Which part is param</p>
</li>
<li><p>Which part is query</p>
</li>
</ul>
<hr />
<h2>Final Thoughts</h2>
<p>URL parameters and query strings are fundamental concepts in Express.js APIs.</p>
<p>The key idea is simple:</p>
<ul>
<li><p>Params identify resources</p>
</li>
<li><p>Query strings modify or filter resources</p>
</li>
</ul>
<p>Understanding when to use each helps you design cleaner and more professional APIs.</p>
<p>As you continue building backend applications, you’ll use params and query strings almost everywhere:</p>
<ul>
<li><p>User systems</p>
</li>
<li><p>Product APIs</p>
</li>
<li><p>Search functionality</p>
</li>
<li><p>Pagination</p>
</li>
<li><p>Filters</p>
</li>
</ul>
<p>Mastering these concepts is an important step toward becoming a strong backend developer.</p>
<hr />
<p>And now, you know what URL Parameters and Query Strings in Express.js are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Storing Uploaded Files and Serving Them in Express]]></title><description><![CDATA[File uploads are a very common feature in modern web applications.
Examples include:

Profile pictures

Documents

PDFs

Product images

Videos


When users upload files, the backend must:

Store the ]]></description><link>https://blogs.abhishekdogra.in/storing-uploaded-files-and-serving-them-in-express</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/storing-uploaded-files-and-serving-them-in-express</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:09:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/b52e266e-b106-40ae-84b5-952d32dc2587.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>File uploads are a very common feature in modern web applications.</p>
<p>Examples include:</p>
<ul>
<li><p>Profile pictures</p>
</li>
<li><p>Documents</p>
</li>
<li><p>PDFs</p>
</li>
<li><p>Product images</p>
</li>
<li><p>Videos</p>
</li>
</ul>
<p>When users upload files, the backend must:</p>
<ol>
<li><p>Store the file safely</p>
</li>
<li><p>Serve the file when needed</p>
</li>
</ol>
<p>In this article, we’ll understand:</p>
<ul>
<li><p>Where uploaded files are stored</p>
</li>
<li><p>Local storage vs external storage</p>
</li>
<li><p>Serving static files in Express</p>
</li>
<li><p>Accessing uploaded files using URLs</p>
</li>
<li><p>Basic security considerations</p>
</li>
</ul>
<p>Let’s start with the basics.</p>
<hr />
<h2>What Happens When a User Uploads a File?</h2>
<p>Suppose a user uploads an image.</p>
<p>The flow usually looks like this:</p>
<pre><code class="language-id=&quot;h2kmbm&quot;">User Uploads File
        ↓
Server Receives File
        ↓
File Stored Somewhere
        ↓
Server Provides URL to Access File
</code></pre>
<p>The backend decides:</p>
<ul>
<li><p>Where the file should be stored</p>
</li>
<li><p>How the file should be served later</p>
</li>
</ul>
<hr />
<h2>Where Are Uploaded Files Stored?</h2>
<p>Uploaded files can be stored in different places.</p>
<p>The two most common approaches are:</p>
<ol>
<li><p>Local Storage</p>
</li>
<li><p>External/Cloud Storage</p>
</li>
</ol>
<hr />
<h2>Local Storage</h2>
<p>In local storage, files are stored directly inside the server project folder.</p>
<p>Example folder structure:</p>
<pre><code class="language-id=&quot;gs1w0i&quot;">project/
│
├── uploads/
│     ├── image1.png
│     ├── profile.jpg
│
├── server.js
</code></pre>
<p>Here:</p>
<ul>
<li><p>Uploaded files go into the <code>uploads</code> folder</p>
</li>
<li><p>The server manages those files directly</p>
</li>
</ul>
<hr />
<h2>Why Local Storage Is Used</h2>
<p>Local storage is useful for:</p>
<p>✅ Small projects ✅ Learning projects ✅ Personal applications ✅ Development environments</p>
<p>It is simple to set up and easy for beginners.</p>
<hr />
<h2>External Storage</h2>
<p>Large applications usually use external cloud storage services.</p>
<p>Examples include:</p>
<ul>
<li><p>AWS S3</p>
</li>
<li><p>Cloudinary</p>
</li>
<li><p>Google Cloud Storage</p>
</li>
</ul>
<p>In this approach:</p>
<pre><code class="language-id=&quot;3z8umv&quot;">Server uploads file to cloud storage
</code></pre>
<p>instead of storing it locally.</p>
<hr />
<h2>Why External Storage Is Used</h2>
<p>External storage helps with:</p>
<p>✅ Scalability ✅ Faster delivery ✅ Better reliability ✅ Reduced server load</p>
<p>This is commonly used in production applications.</p>
<hr />
<h2>Local Storage vs External Storage</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Local Storage</th>
<th>External Storage</th>
</tr>
</thead>
<tbody><tr>
<td>Setup</td>
<td>Simple</td>
<td>More complex</td>
</tr>
<tr>
<td>Scalability</td>
<td>Limited</td>
<td>High</td>
</tr>
<tr>
<td>Best For</td>
<td>Small projects</td>
<td>Large applications</td>
</tr>
<tr>
<td>File Access</td>
<td>From server folder</td>
<td>From cloud URL</td>
</tr>
<tr>
<td>Storage Responsibility</td>
<td>Server</td>
<td>Cloud provider</td>
</tr>
</tbody></table>
<hr />
<h2>Upload Folder Structure</h2>
<p>A clean folder structure is important.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;d70h4y&quot;">project/
│
├── uploads/
│     ├── users/
│     ├── products/
│     ├── documents/
│
├── routes/
├── controllers/
├── server.js
</code></pre>
<p>This keeps uploaded files organized.</p>
<hr />
<h2>Serving Static Files in Express</h2>
<p>By default, Express does not automatically expose files from folders.</p>
<p>To make files publicly accessible, we use:</p>
<pre><code class="language-javascript">express.static()
</code></pre>
<hr />
<h2>Basic Example</h2>
<pre><code class="language-javascript">const express = require("express");

const app = express();

app.use(express.static("uploads"));

app.listen(3000);
</code></pre>
<p>This tells Express:</p>
<pre><code class="language-id=&quot;qtqow7&quot;">"Serve files from the uploads folder"
</code></pre>
<hr />
<h2>How Static File Serving Works</h2>
<p>Suppose this file exists:</p>
<pre><code class="language-id=&quot;39vgj5&quot;">uploads/profile.jpg
</code></pre>
<p>It can now be accessed using:</p>
<pre><code class="language-id=&quot;c31f6r&quot;">http://localhost:3000/profile.jpg
</code></pre>
<p>Express automatically serves the file.</p>
<hr />
<h2>Static File Serving Flow</h2>
<pre><code class="language-id=&quot;n8u55o&quot;">User Requests File URL
          ↓
Express Checks uploads Folder
          ↓
File Found
          ↓
File Sent to Browser
</code></pre>
<hr />
<h2>Serving Files from a Specific Route</h2>
<p>We can also create a custom route.</p>
<p>Example:</p>
<pre><code class="language-javascript">app.use("/uploads", express.static("uploads"));
</code></pre>
<p>Now files are accessed like this:</p>
<pre><code class="language-id=&quot;0xjlwm&quot;">http://localhost:3000/uploads/profile.jpg
</code></pre>
<p>This approach is cleaner and more common.</p>
<hr />
<h2>Example Upload Flow</h2>
<pre><code class="language-id=&quot;yljlwm&quot;">User Uploads image.png
          ↓
File Stored in uploads/
          ↓
Database stores file path
          ↓
Frontend uses image URL
</code></pre>
<p>This is how many real-world applications manage uploaded files.</p>
<hr />
<h2>Accessing Uploaded Files via URL</h2>
<p>Suppose a file is stored as:</p>
<pre><code class="language-id=&quot;2qqm1u&quot;">uploads/avatar.png
</code></pre>
<p>Frontend can access it through:</p>
<pre><code class="language-id=&quot;u2n18q&quot;">http://localhost:3000/uploads/avatar.png
</code></pre>
<p>This URL can be used inside:</p>
<ul>
<li><p><code>&lt;img&gt;</code> tags</p>
</li>
<li><p>API responses</p>
</li>
<li><p>User profile pages</p>
</li>
</ul>
<hr />
<h2>Example Frontend Usage</h2>
<pre><code class="language-html">&lt;img src="http://localhost:3000/uploads/avatar.png" /&gt;
</code></pre>
<p>The browser requests the image from the Express server.</p>
<hr />
<h2>Security Considerations for File Uploads</h2>
<p>File uploads can become dangerous if not handled properly.</p>
<p>Here are some important safety practices.</p>
<hr />
<h2>Validate File Types</h2>
<p>Only allow expected file types.</p>
<p>Example:</p>
<p>✅ Images ✅ PDFs</p>
<p>Avoid accepting unknown executable files.</p>
<hr />
<h2>Limit File Size</h2>
<p>Large uploads can overload the server.</p>
<p>Always set upload size limits.</p>
<hr />
<h2>Rename Uploaded Files</h2>
<p>Avoid using original filenames directly.</p>
<p>Instead of:</p>
<pre><code class="language-id=&quot;5b5b0e&quot;">myphoto.png
</code></pre>
<p>Use unique filenames:</p>
<pre><code class="language-id=&quot;obqsj6&quot;">172839_profile.png
</code></pre>
<p>This prevents conflicts.</p>
<hr />
<h2>Avoid Public Access to Sensitive Files</h2>
<p>Not every uploaded file should be public.</p>
<p>Example:</p>
<ul>
<li><p>Private documents</p>
</li>
<li><p>User identity files</p>
</li>
</ul>
<p>Store sensitive files securely.</p>
<hr />
<h2>Never Trust User Input</h2>
<p>Users may upload harmful files intentionally.</p>
<p>Always validate:</p>
<ul>
<li><p>File type</p>
</li>
<li><p>File size</p>
</li>
<li><p>File extension</p>
</li>
</ul>
<p>on the backend.</p>
<hr />
<h2>Real-World Example</h2>
<p>Imagine a social media app.</p>
<p>Flow:</p>
<pre><code class="language-id=&quot;lyc2wu&quot;">User uploads profile picture
        ↓
Server stores image
        ↓
Image URL saved in database
        ↓
Frontend displays image
</code></pre>
<p>This same pattern is used in many applications.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these tasks yourself.</p>
<hr />
<h2>1. Create an uploads Folder</h2>
<p>Inside your Express project:</p>
<pre><code class="language-id=&quot;t72m9q&quot;">uploads/
</code></pre>
<hr />
<h2>2. Serve Static Files</h2>
<p>Use:</p>
<pre><code class="language-javascript">express.static()
</code></pre>
<p>to expose the uploads folder.</p>
<hr />
<h2>3. Access Files Using URL</h2>
<p>Store a sample image and open it in the browser.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;1t4g44&quot;">http://localhost:3000/uploads/sample.png
</code></pre>
<hr />
<h2>4. Think About Security</h2>
<p>Ask yourself:</p>
<ul>
<li><p>What file types should be allowed?</p>
</li>
<li><p>What happens if users upload huge files?</p>
</li>
<li><p>Should every uploaded file be public?</p>
</li>
</ul>
<p>These questions are important in real-world backend systems.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Handling uploaded files is a core backend development skill.</p>
<p>In Express applications, developers commonly:</p>
<ul>
<li><p>Store files locally or in cloud storage</p>
</li>
<li><p>Serve files using static middleware</p>
</li>
<li><p>Access files through URLs</p>
</li>
<li><p>Protect uploads with validation and security rules</p>
</li>
</ul>
<p>Understanding file storage and static file serving helps you build:</p>
<ul>
<li><p>Social media apps</p>
</li>
<li><p>E-commerce platforms</p>
</li>
<li><p>Portfolio websites</p>
</li>
<li><p>Document management systems</p>
</li>
</ul>
<p>As your projects grow, you’ll eventually move from local storage to cloud-based solutions.</p>
<p>But learning the local Express workflow first builds a strong foundation.</p>
<hr />
<p>And now, you know what storing and serving uploaded files in Express is.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Sessions vs JWT vs Cookies: Understanding Authentication Approaches]]></title><description><![CDATA[Authentication is one of the most important parts of backend development.
Whenever users log in to an application, the server needs a way to remember:

Who the user is

Whether the user is authenticat]]></description><link>https://blogs.abhishekdogra.in/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:05:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/634a0818-1219-4349-9630-31c5e1a3088c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Authentication is one of the most important parts of backend development.</p>
<p>Whenever users log in to an application, the server needs a way to remember:</p>
<ul>
<li><p>Who the user is</p>
</li>
<li><p>Whether the user is authenticated</p>
</li>
<li><p>What actions the user is allowed to perform</p>
</li>
</ul>
<p>This is where:</p>
<ul>
<li><p>Sessions</p>
</li>
<li><p>Cookies</p>
</li>
<li><p>JWT Tokens</p>
</li>
</ul>
<p>come into the picture.</p>
<p>In this article, we’ll understand:</p>
<ul>
<li><p>What sessions are</p>
</li>
<li><p>What cookies are</p>
</li>
<li><p>What JWT tokens are</p>
</li>
<li><p>Stateful vs stateless authentication</p>
</li>
<li><p>Differences between session-based auth and JWT</p>
</li>
<li><p>When to use each approach</p>
</li>
</ul>
<p>Let’s start with the basics.</p>
<hr />
<h2>Why Authentication Is Needed</h2>
<p>Imagine logging into an application.</p>
<p>After login, the server must remember:</p>
<pre><code class="language-id=&quot;c7b7t5&quot;">"User Rahul is authenticated"
</code></pre>
<p>Otherwise, the user would need to log in again on every request.</p>
<p>Authentication systems solve this problem.</p>
<hr />
<h2>What Are Cookies?</h2>
<p>A cookie is a small piece of data stored in the browser.</p>
<p>The server sends cookies to the client, and the browser automatically sends them back with future requests.</p>
<p>Example idea:</p>
<pre><code class="language-id=&quot;wwxjz5&quot;">Server → Browser
"Store this cookie"
</code></pre>
<p>Later:</p>
<pre><code class="language-id=&quot;2hn7j5&quot;">Browser → Server
"Here is the cookie again"
</code></pre>
<p>Cookies help servers identify users across requests.</p>
<hr />
<h2>Simple Cookie Flow</h2>
<pre><code class="language-id=&quot;0ry5rd&quot;">User Logs In
      ↓
Server Creates Cookie
      ↓
Browser Stores Cookie
      ↓
Browser Sends Cookie on Future Requests
</code></pre>
<p>Cookies are commonly used with sessions.</p>
<hr />
<h2>What Are Sessions?</h2>
<p>A session is a server-side storage mechanism used to keep track of logged-in users.</p>
<p>When a user logs in:</p>
<ol>
<li><p>Server creates a session</p>
</li>
<li><p>Server stores user data in memory/database</p>
</li>
<li><p>Server sends a session ID to the browser using a cookie</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="language-id=&quot;6yav2m&quot;">Session ID → abc123
</code></pre>
<p>The browser stores this session ID cookie.</p>
<p>On future requests:</p>
<ul>
<li><p>Browser sends session ID</p>
</li>
<li><p>Server checks session storage</p>
</li>
<li><p>Server identifies the user</p>
</li>
</ul>
<hr />
<h2>Session Authentication Flow</h2>
<pre><code class="language-id=&quot;gkzlg4&quot;">User Logs In
      ↓
Server Creates Session
      ↓
Session Stored on Server
      ↓
Session ID Sent as Cookie
      ↓
Browser Sends Session ID
      ↓
Server Verifies Session
</code></pre>
<hr />
<h2>What Is JWT?</h2>
<p>JWT stands for:</p>
<pre><code class="language-id=&quot;vxvlf0&quot;">JSON Web Token
</code></pre>
<p>A JWT is a token containing user information encoded into a string.</p>
<p>Unlike sessions, JWT authentication is usually <strong>stateless</strong>.</p>
<p>Example JWT structure:</p>
<pre><code class="language-id=&quot;tmg93k&quot;">header.payload.signature
</code></pre>
<p>The token is created by the server and sent to the client.</p>
<p>The client stores the token and sends it with future requests.</p>
<hr />
<h2>JWT Authentication Flow</h2>
<pre><code class="language-id=&quot;6b98a3&quot;">User Logs In
      ↓
Server Creates JWT
      ↓
JWT Sent to Client
      ↓
Client Stores Token
      ↓
Client Sends JWT on Requests
      ↓
Server Verifies Token
</code></pre>
<p>Unlike sessions, the server does not need to store user session data.</p>
<hr />
<h2>Stateful vs Stateless Authentication</h2>
<p>This is one of the most important concepts.</p>
<hr />
<h2>Stateful Authentication</h2>
<p>Sessions are <strong>stateful</strong>.</p>
<p>Meaning:</p>
<pre><code class="language-id=&quot;eh4abz&quot;">Server stores authentication state
</code></pre>
<p>The server remembers logged-in users using session storage.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;k20qmt&quot;">Session stored in database/memory
</code></pre>
<hr />
<h2>Stateless Authentication</h2>
<p>JWT is <strong>stateless</strong>.</p>
<p>Meaning:</p>
<pre><code class="language-id=&quot;6v7q7h&quot;">Server does NOT store user session data
</code></pre>
<p>The token itself contains the required information.</p>
<p>The server only verifies the token.</p>
<hr />
<h2>Sessions vs JWT</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Sessions</th>
<th>JWT</th>
</tr>
</thead>
<tbody><tr>
<td>Storage</td>
<td>Server-side</td>
<td>Client-side</td>
</tr>
<tr>
<td>Authentication Type</td>
<td>Stateful</td>
<td>Stateless</td>
</tr>
<tr>
<td>Scalability</td>
<td>Harder at scale</td>
<td>Easier for distributed systems</td>
</tr>
<tr>
<td>Token/Data Size</td>
<td>Small session ID</td>
<td>Larger token</td>
</tr>
<tr>
<td>Server Memory Usage</td>
<td>Higher</td>
<td>Lower</td>
</tr>
<tr>
<td>Common Usage</td>
<td>Traditional web apps</td>
<td>APIs &amp; modern apps</td>
</tr>
</tbody></table>
<hr />
<h2>Session vs JWT Visual Comparison</h2>
<pre><code class="language-id=&quot;wzv3pq&quot;">SESSION AUTH
Client → Session ID → Server
(Server stores user data)

JWT AUTH
Client → JWT Token → Server
(Token contains user data)
</code></pre>
<hr />
<h2>Real-World Usage of Sessions</h2>
<p>Sessions are commonly used in:</p>
<ul>
<li><p>Traditional web applications</p>
</li>
<li><p>Server-rendered applications</p>
</li>
<li><p>Admin dashboards</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-id=&quot;u3x3ot&quot;">Banking websites
</code></pre>
<p>Sessions are easier to invalidate because data exists on the server.</p>
<hr />
<h2>Real-World Usage of JWT</h2>
<p>JWT is commonly used in:</p>
<ul>
<li><p>REST APIs</p>
</li>
<li><p>Mobile applications</p>
</li>
<li><p>Microservices</p>
</li>
<li><p>Modern frontend-backend architectures</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-id=&quot;nkhm0t&quot;">React + Node.js applications
</code></pre>
<p>JWT works well when frontend and backend are separated.</p>
<hr />
<h2>What About Cookies with JWT?</h2>
<p>Many beginners think:</p>
<pre><code class="language-id=&quot;ytzw7l&quot;">Cookies vs JWT
</code></pre>
<p>But actually:</p>
<pre><code class="language-id=&quot;d18qnm&quot;">Cookies are storage mechanisms
JWT is an authentication token
</code></pre>
<p>JWT can also be stored inside cookies.</p>
<p>Other storage options include:</p>
<ul>
<li><p>localStorage</p>
</li>
<li><p>sessionStorage</p>
</li>
</ul>
<hr />
<h2>When Should You Use Sessions?</h2>
<p>Use sessions when:</p>
<p>✅ Building traditional web apps ✅ Server and frontend are tightly connected ✅ Simpler authentication is preferred ✅ Easy session invalidation is needed</p>
<hr />
<h2>When Should You Use JWT?</h2>
<p>Use JWT when:</p>
<p>✅ Building REST APIs ✅ Frontend and backend are separate ✅ Working with mobile apps ✅ Building scalable distributed systems</p>
<hr />
<h2>Simple Example Comparison</h2>
<h3>Session-Based Authentication</h3>
<pre><code class="language-id=&quot;b9f21m&quot;">Browser stores:
Session ID → abc123

Server stores:
abc123 → Rahul
</code></pre>
<hr />
<h3>JWT Authentication</h3>
<pre><code class="language-id=&quot;0u3h4z&quot;">Browser stores:
JWT Token

Server verifies token signature
</code></pre>
<p>No session storage required.</p>
<hr />
<h2>Advantages of Sessions</h2>
<p>✅ Easier logout handling ✅ Better control on server ✅ Simpler for beginners</p>
<hr />
<h2>Advantages of JWT</h2>
<p>✅ Scalable ✅ No server-side session storage ✅ Great for APIs ✅ Works across multiple services</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try understanding these scenarios.</p>
<hr />
<h2>Scenario 1</h2>
<p>You are building:</p>
<pre><code class="language-id=&quot;b7wt8m&quot;">A simple blog website with server-rendered pages
</code></pre>
<p>Which authentication approach would you choose?</p>
<hr />
<h2>Scenario 2</h2>
<p>You are building:</p>
<pre><code class="language-id=&quot;sg2q78&quot;">A React frontend + Node.js backend API
</code></pre>
<p>Would JWT work better here?</p>
<hr />
<h2>Scenario 3</h2>
<p>Draw your own flow diagram for:</p>
<ul>
<li><p>Session authentication</p>
</li>
<li><p>JWT authentication</p>
</li>
</ul>
<p>This will help you visualize the process clearly.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Authentication is a core part of backend development.</p>
<p>Understanding:</p>
<ul>
<li><p>Cookies</p>
</li>
<li><p>Sessions</p>
</li>
<li><p>JWT</p>
</li>
</ul>
<p>helps you build secure and scalable applications.</p>
<p>Key takeaway:</p>
<ul>
<li><p>Sessions are <strong>stateful</strong></p>
</li>
<li><p>JWT is <strong>stateless</strong></p>
</li>
<li><p>Cookies are simply a way to store data in the browser</p>
</li>
</ul>
<p>There is no “best” approach for every situation.</p>
<p>The right choice depends on:</p>
<ul>
<li><p>Application architecture</p>
</li>
<li><p>Scalability needs</p>
</li>
<li><p>Frontend-backend structure</p>
</li>
<li><p>User experience requirements</p>
</li>
</ul>
<p>As you continue learning Node.js, you’ll encounter these authentication approaches in almost every real-world application.</p>
<hr />
<p>And now, you know what Sessions, JWT, and Cookies are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[Working with strings is something we do very often in JavaScript.
For example:

Displaying user names

Creating messages

Building HTML dynamically

Showing API data


Before template literals were in]]></description><link>https://blogs.abhishekdogra.in/template-literals-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/template-literals-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 12:00:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/cd36166d-d768-415e-8288-1e346bbe077e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Working with strings is something we do very often in JavaScript.</p>
<p>For example:</p>
<ul>
<li><p>Displaying user names</p>
</li>
<li><p>Creating messages</p>
</li>
<li><p>Building HTML dynamically</p>
</li>
<li><p>Showing API data</p>
</li>
</ul>
<p>Before template literals were introduced, combining strings and variables was not very clean.</p>
<p>Template literals made string handling much easier and more readable.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>Problems with traditional string concatenation</p>
</li>
<li><p>Template literal syntax</p>
</li>
<li><p>Embedding variables in strings</p>
</li>
<li><p>Multi-line strings</p>
</li>
<li><p>Real-world use cases in modern JavaScript</p>
</li>
</ul>
<p>Let’s begin with the older approach first.</p>
<hr />
<h2>Problems with Traditional String Concatenation</h2>
<p>Before template literals, developers used the <code>+</code> operator to combine strings.</p>
<p>Example:</p>
<pre><code class="language-javascript">let name = "Rahul";

let message = "Hello " + name + ", welcome to JavaScript.";

console.log(message);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;1rj68s&quot;">Hello Rahul, welcome to JavaScript.
</code></pre>
<p>This works, but when strings become larger, the code becomes difficult to read.</p>
<p>Example:</p>
<pre><code class="language-javascript">let product = "Laptop";
let price = 50000;

let text = "The product " + product + " costs Rs. " + price;
</code></pre>
<p>Too many <code>+</code> signs reduce readability.</p>
<hr />
<h2>What Are Template Literals?</h2>
<p>Template literals are a modern way to work with strings in JavaScript.</p>
<p>They use:</p>
<pre><code class="language-id=&quot;wn4f1w&quot;">Backticks (` `)
</code></pre>
<p>instead of normal quotes.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">let text = `Hello World`;
</code></pre>
<p>Template literals make strings cleaner and easier to write.</p>
<hr />
<h2>Embedding Variables in Strings</h2>
<p>One of the best features of template literals is <strong>string interpolation</strong>.</p>
<p>Instead of using <code>+</code>, we can directly insert variables using:</p>
<pre><code class="language-id=&quot;x1drgo&quot;">${variable}
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">let name = "Rahul";

let message = `Hello ${name}, welcome to JavaScript.`;

console.log(message);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;y6rz4u&quot;">Hello Rahul, welcome to JavaScript.
</code></pre>
<hr />
<h2>Before vs After Template Literals</h2>
<h3>Old String Concatenation</h3>
<pre><code class="language-javascript">let name = "Rahul";
let age = 22;

let text = "My name is " + name + " and I am " + age + " years old.";
</code></pre>
<hr />
<h3>Using Template Literals</h3>
<pre><code class="language-javascript">let name = "Rahul";
let age = 22;

let text = `My name is \({name} and I am \){age} years old.`;
</code></pre>
<p>The second version is:</p>
<ul>
<li><p>Cleaner</p>
</li>
<li><p>Easier to read</p>
</li>
<li><p>Easier to maintain</p>
</li>
</ul>
<hr />
<h2>String Interpolation Visualization</h2>
<pre><code class="language-id=&quot;7j1h6s&quot;">`Hello ${name}`

        ↓

Variable value inserted into string
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">name = "Rahul"

Result:
"Hello Rahul"
</code></pre>
<hr />
<h2>Multi-Line Strings</h2>
<p>Before template literals, multi-line strings were difficult to write.</p>
<p>Example using old approach:</p>
<pre><code class="language-javascript">let text = "Hello\n" +
           "Welcome\n" +
           "To JavaScript";
</code></pre>
<p>Template literals make this much simpler.</p>
<p>Example:</p>
<pre><code class="language-javascript">let text = `
Hello
Welcome
To JavaScript
`;

console.log(text);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;rkgk0u&quot;">Hello
Welcome
To JavaScript
</code></pre>
<p>No need for <code>\n</code> or <code>+</code>.</p>
<hr />
<h2>Expressions Inside Template Literals</h2>
<p>We can also run JavaScript expressions inside <code>${}</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">let a = 5;
let b = 10;

console.log(`Sum is ${a + b}`);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;p8jmf0&quot;">Sum is 15
</code></pre>
<p>This makes template literals very powerful.</p>
<hr />
<h2>Real-World Use Cases</h2>
<p>Template literals are heavily used in modern JavaScript applications.</p>
<h3>Creating Dynamic Messages</h3>
<pre><code class="language-javascript">let username = "Aman";

console.log(`Welcome back, ${username}!`);
</code></pre>
<hr />
<h3>Building HTML</h3>
<pre><code class="language-javascript">let title = "JavaScript";

let html = `
  &lt;h1&gt;${title}&lt;/h1&gt;
`;
</code></pre>
<hr />
<h3>API Responses</h3>
<pre><code class="language-javascript">let product = "Phone";
let price = 30000;

console.log(`\({product} costs Rs. \){price}`);
</code></pre>
<hr />
<h2>Why Template Literals Are Better</h2>
<p>Template literals improve:</p>
<h3>Readability</h3>
<p>Cleaner and easier to understand.</p>
<h3>Maintainability</h3>
<p>Less messy compared to concatenation.</p>
<h3>Multi-Line Support</h3>
<p>Writing long strings becomes simple.</p>
<h3>Dynamic Content</h3>
<p>Variables and expressions can be inserted easily.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises in your browser console.</p>
<hr />
<h2>1. Create a Greeting Message</h2>
<pre><code class="language-javascript">let name = "Rahul";

let message = `Hello ${name}`;

console.log(message);
</code></pre>
<hr />
<h2>2. Use Expressions</h2>
<pre><code class="language-javascript">let a = 10;
let b = 20;

console.log(`Total is ${a + b}`);
</code></pre>
<hr />
<h2>3. Create a Multi-Line String</h2>
<pre><code class="language-javascript">let text = `
JavaScript
is
awesome!
`;

console.log(text);
</code></pre>
<hr />
<h2>4. Compare Old vs New Approach</h2>
<p>Write the same string using:</p>
<ul>
<li><p>string concatenation</p>
</li>
<li><p>template literals</p>
</li>
</ul>
<p>Observe which one looks cleaner.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Template literals are one of the most useful modern JavaScript features.</p>
<p>They help developers:</p>
<ul>
<li><p>Write cleaner strings</p>
</li>
<li><p>Insert variables easily</p>
</li>
<li><p>Create multi-line text</p>
</li>
<li><p>Improve readability</p>
</li>
</ul>
<p>Today, template literals are widely used in:</p>
<ul>
<li><p>Frontend development</p>
</li>
<li><p>Backend applications</p>
</li>
<li><p>React projects</p>
</li>
<li><p>API handling</p>
</li>
</ul>
<p>Once you start using them, going back to traditional string concatenation feels difficult.</p>
<hr />
<p>And now, you know what Template Literals in JavaScript are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Modules: Import and Export Explained]]></title><description><![CDATA[As JavaScript applications grow larger, managing all code inside a single file becomes difficult.
Imagine writing everything in one file:

Functions

Variables

API logic

Utility functions


The file]]></description><link>https://blogs.abhishekdogra.in/javascript-modules-import-and-export-explained</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/javascript-modules-import-and-export-explained</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 11:56:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/aa07dc1f-e0d2-46c0-ad3a-a58cad3923b2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As JavaScript applications grow larger, managing all code inside a single file becomes difficult.</p>
<p>Imagine writing everything in one file:</p>
<ul>
<li><p>Functions</p>
</li>
<li><p>Variables</p>
</li>
<li><p>API logic</p>
</li>
<li><p>Utility functions</p>
</li>
</ul>
<p>The file would quickly become messy and hard to maintain.</p>
<p>To solve this problem, JavaScript provides <strong>modules</strong>.</p>
<p>Modules help us split code into smaller, reusable files.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>Why modules are needed</p>
</li>
<li><p>How to export functions or values</p>
</li>
<li><p>How to import modules</p>
</li>
<li><p>Default vs named exports</p>
</li>
<li><p>Benefits of modular code</p>
</li>
</ul>
<p>Let’s begin with the problem first.</p>
<hr />
<h2>Why Are Modules Needed?</h2>
<p>Suppose we have one large file:</p>
<pre><code class="language-javascript">function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

// hundreds of more lines...
</code></pre>
<p>As applications grow:</p>
<ul>
<li><p>Files become very large</p>
</li>
<li><p>Code becomes difficult to read</p>
</li>
<li><p>Reusing code becomes harder</p>
</li>
<li><p>Bugs become difficult to track</p>
</li>
</ul>
<p>This is where modules help.</p>
<hr />
<h2>What Is a Module?</h2>
<p>A module is simply a separate JavaScript file that contains related code.</p>
<p>Example:</p>
<pre><code class="language-id=&quot;n1wyt7&quot;">math.js
app.js
user.js
</code></pre>
<p>Each file handles a specific responsibility.</p>
<p>This improves:</p>
<ul>
<li><p>Code organization</p>
</li>
<li><p>Reusability</p>
</li>
<li><p>Maintainability</p>
</li>
</ul>
<hr />
<h2>Exporting Functions or Values</h2>
<p>To use code from another file, we first need to <strong>export</strong> it.</p>
<p>Example:</p>
<h3>math.js</h3>
<pre><code class="language-javascript">export const add = (a, b) =&gt; {
  return a + b;
};
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>add</code> is exported</p>
</li>
<li><p>Other files can now use it</p>
</li>
</ul>
<p>We can also export variables.</p>
<p>Example:</p>
<pre><code class="language-javascript">export const pi = 3.14;
</code></pre>
<hr />
<h2>Importing Modules</h2>
<p>To use exported code, we use <code>import</code>.</p>
<p>Example:</p>
<h3>app.js</h3>
<pre><code class="language-javascript">import { add } from "./math.js";

console.log(add(2, 3));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;h1br5x&quot;">5
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>add</code> is imported from <code>math.js</code></p>
</li>
<li><p>We can now use it in another file</p>
</li>
</ul>
<hr />
<h2>Module Import/Export Flow</h2>
<pre><code class="language-id=&quot;mjlwmx&quot;">math.js
   │
   │ export add()
   ↓
app.js
   │
   │ import add()
   ↓
Use the function
</code></pre>
<p>Modules allow files to communicate cleanly.</p>
<hr />
<h2>Named Exports</h2>
<p>Named exports allow exporting multiple values from the same file.</p>
<p>Example:</p>
<h3>math.js</h3>
<pre><code class="language-javascript">export const add = (a, b) =&gt; a + b;

export const subtract = (a, b) =&gt; a - b;
</code></pre>
<p>Importing:</p>
<pre><code class="language-javascript">import { add, subtract } from "./math.js";

console.log(add(5, 2));
console.log(subtract(5, 2));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;4c6bpu&quot;">7
3
</code></pre>
<p>Notice the curly braces <code>{}</code>.</p>
<p>They are required for named exports.</p>
<hr />
<h2>Default Export</h2>
<p>A file can also have one <strong>default export</strong>.</p>
<p>Example:</p>
<h3>greet.js</h3>
<pre><code class="language-javascript">export default function greet(name) {
  return "Hello " + name;
}
</code></pre>
<p>Importing:</p>
<pre><code class="language-javascript">import greet from "./greet.js";

console.log(greet("Rahul"));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;nfhf1j&quot;">Hello Rahul
</code></pre>
<hr />
<h2>Default vs Named Export</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Named Export</th>
<th>Default Export</th>
</tr>
</thead>
<tbody><tr>
<td>Multiple exports allowed</td>
<td>✅ Yes</td>
<td>❌ No</td>
</tr>
<tr>
<td>Curly braces needed while importing</td>
<td>✅ Yes</td>
<td>❌ No</td>
</tr>
<tr>
<td>Import name must match</td>
<td>✅ Usually</td>
<td>❌ Can be renamed</td>
</tr>
</tbody></table>
<hr />
<h2>Example Comparison</h2>
<h3>Named Export</h3>
<pre><code class="language-javascript">export const add = (a, b) =&gt; a + b;
</code></pre>
<p>Import:</p>
<pre><code class="language-javascript">import { add } from "./math.js";
</code></pre>
<hr />
<h3>Default Export</h3>
<pre><code class="language-javascript">export default function greet() {
  console.log("Hello");
}
</code></pre>
<p>Import:</p>
<pre><code class="language-javascript">import greet from "./greet.js";
</code></pre>
<hr />
<h2>Benefits of Modular Code</h2>
<p>Modules provide many advantages.</p>
<h3>Better Organization</h3>
<p>Each file has a specific responsibility.</p>
<h3>Easier Maintenance</h3>
<p>Fixing bugs becomes easier because code is separated.</p>
<h3>Code Reusability</h3>
<p>The same module can be reused in multiple files.</p>
<h3>Cleaner Projects</h3>
<p>Large applications remain structured and manageable.</p>
<hr />
<h2>File Dependency Diagram</h2>
<pre><code class="language-id=&quot;0yrqk3&quot;">app.js
 │
 ├── imports math.js
 ├── imports user.js
 └── imports api.js
</code></pre>
<p>Each module handles a separate part of the application.</p>
<hr />
<h2>Real-World Example</h2>
<p>Imagine building an e-commerce app.</p>
<p>Instead of one huge file:</p>
<pre><code class="language-id=&quot;dcbn13&quot;">everything.js
</code></pre>
<p>We can split code into modules:</p>
<pre><code class="language-id=&quot;9hklpb&quot;">cart.js
payment.js
products.js
auth.js
</code></pre>
<p>This structure is much easier to manage.</p>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h2>1. Create a Module</h2>
<p>Create a file called <code>math.js</code>.</p>
<p>Export:</p>
<ul>
<li><p><code>add()</code></p>
</li>
<li><p><code>multiply()</code></p>
</li>
</ul>
<hr />
<h2>2. Import Functions</h2>
<p>Create another file called <code>app.js</code>.</p>
<p>Import the functions and call them.</p>
<hr />
<h2>3. Try Default Export</h2>
<p>Export a greeting function as default and import it into another file.</p>
<hr />
<h2>4. Experiment</h2>
<p>Try:</p>
<ul>
<li><p>named exports</p>
</li>
<li><p>default exports</p>
</li>
<li><p>multiple imports</p>
</li>
</ul>
<p>This will help you understand module flow better.</p>
<hr />
<h2>Final Thoughts</h2>
<p>JavaScript modules are one of the most important features in modern development.</p>
<p>They help developers:</p>
<ul>
<li><p>Organize code better</p>
</li>
<li><p>Reuse logic easily</p>
</li>
<li><p>Build scalable applications</p>
</li>
<li><p>Maintain clean project structures</p>
</li>
</ul>
<p>As your projects grow larger, modular code becomes extremely important.</p>
<p>Start practicing modules early, and your JavaScript projects will become much easier to manage.</p>
<hr />
<p>And now, you know what JavaScript Modules and Import/Export are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in JavaScript]]></title><description><![CDATA[Arrays are one of the most commonly used data structures in JavaScript. Sometimes, arrays can contain other arrays inside them. These are called nested arrays.
Working with nested arrays is very commo]]></description><link>https://blogs.abhishekdogra.in/array-flatten-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/array-flatten-in-javascript</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 11:30:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/d9106b93-8a51-4bf1-9e52-36a2280b8be1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Arrays are one of the most commonly used data structures in JavaScript. Sometimes, arrays can contain other arrays inside them. These are called <strong>nested arrays</strong>.</p>
<p>Working with nested arrays is very common in real-world applications and coding interviews.</p>
<p>In this article, we’ll learn:</p>
<ul>
<li><p>What nested arrays are</p>
</li>
<li><p>Why flattening arrays is useful</p>
</li>
<li><p>What array flattening means</p>
</li>
<li><p>Different ways to flatten arrays</p>
</li>
<li><p>Common interview scenarios</p>
</li>
</ul>
<p>Let’s start with the basics.</p>
<hr />
<h3>What Are Nested Arrays?</h3>
<p>A nested array is simply an array that contains other arrays inside it.</p>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, 2, [3, 4], [5, 6]];
</code></pre>
<p>Visual representation:</p>
<pre><code class="language-id=&quot;5j3d33&quot;">[
  1,
  2,
  [3, 4],
  [5, 6]
]
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>1</code> and <code>2</code> are normal elements</p>
</li>
<li><p><code>[3, 4]</code> and <code>[5, 6]</code> are arrays inside the main array</p>
</li>
</ul>
<hr />
<h3>Why Is Flattening Arrays Useful?</h3>
<p>Sometimes we want all elements in a <strong>single array</strong> instead of nested arrays.</p>
<p>Example:</p>
<pre><code class="language-javascript">[1, 2, [3, 4]]
</code></pre>
<p>Flattened version:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<p>Flattening is useful when:</p>
<ul>
<li><p>Processing API data</p>
</li>
<li><p>Working with matrix-like structures</p>
</li>
<li><p>Preparing data for loops</p>
</li>
<li><p>Solving coding interview problems</p>
</li>
</ul>
<hr />
<h3>What Does Flattening Mean?</h3>
<p>Flattening means converting:</p>
<pre><code class="language-id=&quot;zq52h6&quot;">Nested Array
      ↓
Single-Level Array
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, [2, [3, 4]]];
</code></pre>
<p>Flattened result:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<hr />
<h3>Visual Transformation</h3>
<pre><code class="language-id=&quot;x7c2z6&quot;">[1, [2, [3, 4]], 5]

        ↓

[1, 2, 3, 4, 5]
</code></pre>
<p>The nested structure becomes a simple flat array.</p>
<hr />
<h3>Approach 1: Using <code>flat()</code></h3>
<p>JavaScript provides a built-in method called <code>flat()</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, 2, [3, 4]];

let result = arr.flat();

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;uw4g8k&quot;">[1, 2, 3, 4]
</code></pre>
<hr />
<h3>Flattening Deeper Arrays</h3>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, [2, [3, 4]]];

console.log(arr.flat(2));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;nd6exl&quot;">[1, 2, 3, 4]
</code></pre>
<p>The number <code>2</code> tells JavaScript how deep to flatten.</p>
<hr />
<h3>Using <code>Infinity</code></h3>
<p>If we don’t know the depth, we can use <code>Infinity</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, [2, [3, [4, 5]]]];

console.log(arr.flat(Infinity));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;dn71jm&quot;">[1, 2, 3, 4, 5]
</code></pre>
<hr />
<h3>Approach 2: Using a Loop</h3>
<p>We can flatten arrays manually using loops.</p>
<p>Example:</p>
<pre><code class="language-javascript">let arr = [1, 2, [3, 4]];

let result = [];

for (let element of arr) {
  if (Array.isArray(element)) {
    for (let item of element) {
      result.push(item);
    }
  } else {
    result.push(element);
  }
}

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;7hsggq&quot;">[1, 2, 3, 4]
</code></pre>
<p>This approach helps us understand the flattening process step by step.</p>
<hr />
<h3>Step-by-Step Thinking</h3>
<p>Example:</p>
<pre><code class="language-javascript">[1, [2, 3], 4]
</code></pre>
<p>Process:</p>
<pre><code class="language-id=&quot;50vb77&quot;">Take 1 → add to result

Take [2,3]
  → extract 2
  → extract 3

Take 4 → add to result
</code></pre>
<p>Final result:</p>
<pre><code class="language-id=&quot;4p1ytm&quot;">[1, 2, 3, 4]
</code></pre>
<p>This problem-solving approach is important for interviews.</p>
<hr />
<h3>Approach 3: Using Recursion</h3>
<p>Recursion is commonly used for deeply nested arrays.</p>
<p>Example:</p>
<pre><code class="language-javascript">function flattenArray(arr) {
  let result = [];

  for (let element of arr) {
    if (Array.isArray(element)) {
      result = result.concat(flattenArray(element));
    } else {
      result.push(element);
    }
  }

  return result;
}

let arr = [1, [2, [3, 4]], 5];

console.log(flattenArray(arr));
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;m4m5px&quot;">[1, 2, 3, 4, 5]
</code></pre>
<hr />
<h3>How Recursion Works</h3>
<pre><code class="language-id=&quot;4d2n6r&quot;">flatten([1,[2,[3]]])

→ take 1
→ flatten([2,[3]])
       → take 2
       → flatten([3])
              → take 3
</code></pre>
<p>The function keeps going deeper until all nested arrays are processed.</p>
<hr />
<h3>Common Interview Scenarios</h3>
<p>Array flattening is a very popular interview question.</p>
<p>Interviewers may ask:</p>
<ul>
<li><p>Flatten an array without using <code>flat()</code></p>
</li>
<li><p>Flatten only one level</p>
</li>
<li><p>Flatten deeply nested arrays</p>
</li>
<li><p>Write a recursive solution</p>
</li>
<li><p>Optimize the flattening process</p>
</li>
</ul>
<p>Example interview input:</p>
<pre><code class="language-javascript">[1, [2, [3, [4]]]]
</code></pre>
<p>Expected output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<hr />
<h3><code>flat()</code> vs Recursive Approach</h3>
<table>
<thead>
<tr>
<th>Method</th>
<th>Easy to Write</th>
<th>Handles Deep Nesting</th>
<th>Interview Friendly</th>
</tr>
</thead>
<tbody><tr>
<td><code>flat()</code></td>
<td>✅</td>
<td>✅</td>
<td>❌</td>
</tr>
<tr>
<td>Loop</td>
<td>✅</td>
<td>❌</td>
<td>✅</td>
</tr>
<tr>
<td>Recursion</td>
<td>Moderate</td>
<td>✅</td>
<td>✅</td>
</tr>
</tbody></table>
<hr />
<h2>Practice Assignment</h2>
<p>Try these exercises yourself.</p>
<hr />
<h3>1. Flatten One Level</h3>
<p>Input:</p>
<pre><code class="language-javascript">[1, 2, [3, 4]]
</code></pre>
<p>Expected Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<hr />
<h3>2. Flatten Deeply Nested Arrays</h3>
<p>Input:</p>
<pre><code class="language-javascript">[1, [2, [3, [4, 5]]]]
</code></pre>
<p>Expected Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4, 5]
</code></pre>
<hr />
<h3>3. Try Without Using <code>flat()</code></h3>
<p>Use:</p>
<ul>
<li><p>loops</p>
</li>
<li><p>recursion</p>
</li>
<li><p><code>concat()</code></p>
</li>
</ul>
<p>This will improve your problem-solving skills.</p>
<hr />
<p>And now, you know what Array Flatten in JavaScript is.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Async Code in Node.js: Callbacks and Promises]]></title><description><![CDATA[When building applications in Node.js, many operations take time to complete.
Examples:

Reading files

Fetching data from APIs

Connecting to databases

Waiting for user input


If Node.js waited for]]></description><link>https://blogs.abhishekdogra.in/async-code-in-node-js-callbacks-and-promises</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/async-code-in-node-js-callbacks-and-promises</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sat, 09 May 2026 11:26:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/72034789-e1a1-4b5d-ab61-bafab25037d0.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building applications in Node.js, many operations take time to complete.</p>
<p>Examples:</p>
<ul>
<li><p>Reading files</p>
</li>
<li><p>Fetching data from APIs</p>
</li>
<li><p>Connecting to databases</p>
</li>
<li><p>Waiting for user input</p>
</li>
</ul>
<p>If Node.js waited for each task to finish before moving forward, applications would become slow and inefficient.</p>
<p>This is why Node.js uses <strong>asynchronous code</strong>.</p>
<p>In this article, we’ll understand:</p>
<ul>
<li><p>Why async code exists in Node.js</p>
</li>
<li><p>Callback-based asynchronous execution</p>
</li>
<li><p>Problems with nested callbacks</p>
</li>
<li><p>Promise-based async handling</p>
</li>
<li><p>Benefits of promises</p>
</li>
</ul>
<p>Let’s begin with a real-world example.</p>
<hr />
<h2>Why Does Async Code Exist in Node.js?</h2>
<p>Imagine reading a large file from your computer.</p>
<p>If Node.js stopped everything until the file finished loading, the entire application would freeze.</p>
<p>Instead, Node.js starts the file-reading task and continues doing other work.</p>
<p>When the file is ready, Node.js handles the result later.</p>
<p>This is called <strong>asynchronous programming</strong>.</p>
<hr />
<h3>Synchronous vs Asynchronous Code</h3>
<h3>Synchronous Code</h3>
<pre><code class="language-javascript">console.log("Start");

console.log("Reading file...");

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;rj77zn&quot;">Start
Reading file...
End
</code></pre>
<p>The code runs line by line in order.</p>
<hr />
<h3>Asynchronous Example</h3>
<p>Node.js provides asynchronous functions like <code>fs.readFile()</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

console.log("Start");

fs.readFile("demo.txt", "utf8", (err, data) =&gt; {
  console.log(data);
});

console.log("End");
</code></pre>
<p>Possible output:</p>
<pre><code class="language-id=&quot;w7y2mk&quot;">Start
End
File content here
</code></pre>
<p>Notice:</p>
<ul>
<li><p>Node.js does not wait for the file to finish reading</p>
</li>
<li><p>It continues executing the next lines</p>
</li>
<li><p>The callback runs later when the file is ready</p>
</li>
</ul>
<hr />
<h2>What is a Callback?</h2>
<p>A <strong>callback</strong> is a function passed into another function to run later.</p>
<p>Example:</p>
<pre><code class="language-javascript">function greet(name, callback) {
  console.log("Hello " + name);

  callback();
}

function sayBye() {
  console.log("Goodbye");
}

greet("Abhi", sayBye);
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;5dr4u7&quot;">Hello Abhi
Goodbye
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>sayBye</code> is passed as a callback</p>
</li>
<li><p>It executes after the greeting</p>
</li>
</ul>
<hr />
<h3>Callback-Based Async Execution</h3>
<p>Let’s understand async flow step by step.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs");

console.log("1. Start Reading");

fs.readFile("demo.txt", "utf8", (err, data) =&gt; {
  console.log("2. File Content:", data);
});

console.log("3. Continue Execution");
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;m4lmv9&quot;">1. Start Reading
3. Continue Execution
2. File Content: Hello World
</code></pre>
<hr />
<h3>How the Callback Flow Works</h3>
<pre><code class="language-id=&quot;3mwpx5&quot;">Start Program
      ↓
Start File Reading
      ↓
Continue Other Code
      ↓
File Reading Completes
      ↓
Callback Function Executes
</code></pre>
<p>This is the foundation of asynchronous programming in Node.js.</p>
<hr />
<h3>Problems with Nested Callbacks</h3>
<p>Callbacks work well initially, but deeply nested callbacks can make code difficult to read.</p>
<p>Example:</p>
<pre><code class="language-javascript">loginUser(function(user) {
  getPosts(user, function(posts) {
    getComments(posts, function(comments) {
      console.log(comments);
    });
  });
});
</code></pre>
<p>This structure becomes hard to manage.</p>
<p>This problem is often called:</p>
<pre><code class="language-id=&quot;ym1iw9&quot;">Callback Hell
</code></pre>
<p>Problems include:</p>
<ul>
<li><p>Hard to read</p>
</li>
<li><p>Difficult to debug</p>
</li>
<li><p>Deep nesting</p>
</li>
<li><p>Poor maintainability</p>
</li>
</ul>
<hr />
<h2>Introduction to Promises</h2>
<p>Promises were introduced to make asynchronous code cleaner and easier to manage.</p>
<p>A Promise represents a value that may be available:</p>
<ul>
<li><p>Now</p>
</li>
<li><p>Later</p>
</li>
<li><p>Or never</p>
</li>
</ul>
<hr />
<h3>Creating a Promise</h3>
<p>Example:</p>
<pre><code class="language-javascript">const promise = new Promise((resolve, reject) =&gt; {
  let success = true;

  if (success) {
    resolve("Operation Successful");
  } else {
    reject("Operation Failed");
  }
});
</code></pre>
<p>A promise has two possible outcomes:</p>
<ul>
<li><p><code>resolve()</code> → success</p>
</li>
<li><p><code>reject()</code> → failure</p>
</li>
</ul>
<hr />
<h3>Handling Promises</h3>
<p>We use:</p>
<ul>
<li><p><code>.then()</code> for success</p>
</li>
<li><p><code>.catch()</code> for errors</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">promise
  .then((message) =&gt; {
    console.log(message);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>Output:</p>
<pre><code class="language-id=&quot;o5b3p2&quot;">Operation Successful
</code></pre>
<hr />
<h2>Promise-Based Async Handling</h2>
<p>Let’s rewrite a file-reading example using promises.</p>
<p>Example:</p>
<pre><code class="language-javascript">const fs = require("fs").promises;

fs.readFile("demo.txt", "utf8")
  .then((data) =&gt; {
    console.log(data);
  })
  .catch((err) =&gt; {
    console.log(err);
  });
</code></pre>
<p>This looks cleaner compared to nested callbacks.</p>
<hr />
<h2>Callback vs Promise Readability</h2>
<h2>Callback Style</h2>
<pre><code class="language-javascript">getUser(function(user) {
  getOrders(user, function(orders) {
    console.log(orders);
  });
});
</code></pre>
<hr />
<h3>Promise Style</h3>
<pre><code class="language-javascript">getUser()
  .then((user) =&gt; getOrders(user))
  .then((orders) =&gt; console.log(orders))
  .catch((err) =&gt; console.log(err));
</code></pre>
<p>Promises reduce nesting and improve readability.</p>
<hr />
<h3>Benefits of Promises</h3>
<p>Promises provide several advantages:</p>
<p>✅ Cleaner code</p>
<p>✅ Better readability</p>
<p>✅ Easier error handling</p>
<p>✅ Avoid callback hell</p>
<p>✅ Better async chaining</p>
<p>This is why modern Node.js applications heavily use promises.</p>
<hr />
<h3>Promise Lifecycle</h3>
<p>A promise has three states.</p>
<pre><code class="language-id=&quot;z0ajz7&quot;">Pending
   ↓
Resolved  OR  Rejected
</code></pre>
<h3>States</h3>
<table>
<thead>
<tr>
<th>State</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>Pending</td>
<td>Operation still running</td>
</tr>
<tr>
<td>Resolved</td>
<td>Operation successful</td>
</tr>
<tr>
<td>Rejected</td>
<td>Operation failed</td>
</tr>
</tbody></table>
<hr />
<h2>Practice Assignment</h2>
<p>Try these tasks yourself.</p>
<hr />
<h3>1. Callback Example</h3>
<p>Create a function that waits 2 seconds and then prints a message using a callback.</p>
<p>Example:</p>
<pre><code class="language-javascript">function fetchData(callback) {
  setTimeout(() =&gt; {
    callback("Data received");
  }, 2000);
}
</code></pre>
<hr />
<h3>2. Promise Example</h3>
<p>Create a promise that resolves after 2 seconds.</p>
<p>Example:</p>
<pre><code class="language-javascript">const promise = new Promise((resolve) =&gt; {
  setTimeout(() =&gt; {
    resolve("Data loaded");
  }, 2000);
});
</code></pre>
<hr />
<h3>3. Handle the Promise</h3>
<p>Use <code>.then()</code> to print the resolved value.</p>
<hr />
<p>And now, you know what Callbacks and Promises in Node.js are.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[The Magic of this, call(), apply(), and bind() in JavaScript]]></title><description><![CDATA[Hey Everyone,
In this blog, we will learn about call(), apply(), and bind() in JavaScript.
One concept that confuses many JavaScript beginners is the keyword this.
Understanding how this works — and h]]></description><link>https://blogs.abhishekdogra.in/the-magic-of-this-call-apply-and-bind-in-javascript</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/the-magic-of-this-call-apply-and-bind-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[ChaiCohort]]></category><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sun, 15 Mar 2026 17:16:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/0e4e2733-1aef-49c8-a0ca-2c57f93b9ffe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey Everyone,</p>
<p>In this blog, we will learn about call(), apply(), and bind() in JavaScript.</p>
<p>One concept that confuses many JavaScript beginners is the keyword <code>this</code>.</p>
<p>Understanding how <code>this</code> works — and how <code>call()</code>, <code>apply()</code>, and <code>bind()</code> control it — is an important step toward writing better JavaScript.</p>
<hr />
<h3>What Does <code>this</code> Mean?</h3>
<p>In JavaScript, <code>this</code> <strong>refers to the object that is calling the function</strong>.</p>
<p>Think of it as answering the question:</p>
<p>👉 <strong>“Who is calling this function?”</strong></p>
<p>Example:</p>
<pre><code class="language-javascript">const person = {
  name: "Rahul",
  greet() {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello, my name is Rahul
</code></pre>
<p>Here:</p>
<ul>
<li><p>The function <code>greet()</code> is called by <code>person</code></p>
</li>
<li><p>So <code>this</code> <strong>refers to</strong> <code>person</code></p>
</li>
</ul>
<hr />
<h3><code>this</code> Inside Normal Functions</h3>
<p>Inside a regular function, <code>this</code> usually refers to the <strong>global object</strong> (or <code>undefined</code> in strict mode).</p>
<p>Example:</p>
<pre><code class="language-javascript">function show() {
  console.log(this);
}

show();
</code></pre>
<p>In a browser environment, <code>this</code> typically refers to the <strong>window object</strong>.</p>
<p>The key idea is:</p>
<p>👉 <code>this</code> depends on <strong>how the function is called</strong>, not where it is written.</p>
<hr />
<h3><code>this</code> Inside Objects</h3>
<p>When a function is called as a <strong>method of an object</strong>, <code>this</code> refers to that object.</p>
<p>Example:</p>
<pre><code class="language-javascript">const car = {
  brand: "Toyota",
  showBrand() {
    console.log(this.brand);
  }
};

car.showBrand();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Toyota
</code></pre>
<p>Here <code>this.brand</code> refers to <code>car.brand</code>.</p>
<hr />
<h3>What Does <code>call()</code> Do?</h3>
<p>The <code>call()</code> method allows us to <strong>manually set the value of</strong> <code>this</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">const person1 = {
  name: "Rahul"
};

const person2 = {
  name: "Anita"
};

function greet() {
  console.log("Hello " + this.name);
}

greet.call(person1);
greet.call(person2);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Rahul
Hello Anita
</code></pre>
<p><code>call()</code> lets us choose <strong>which object should be</strong> <code>this</code>.</p>
<hr />
<h3>What Does <code>apply()</code> Do?</h3>
<h3><code>apply()</code> works almost the same as <code>call()</code>.</h3>
<p>The difference is <strong>how arguments are passed</strong>.</p>
<p>Example:</p>
<pre><code class="language-javascript">function introduce(city, country) {
  console.log(this.name + " from " + city + ", " + country);
}

const person = { name: "Rahul" };

introduce.apply(person, ["Delhi", "India"]);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Rahul from Delhi, India
</code></pre>
<p>Here arguments are passed as an <strong>array</strong>.</p>
<hr />
<h3>What Does <code>bind()</code> Do?</h3>
<p><code>bind()</code> also sets the value of <code>this</code>, but it <strong>returns a new function instead of calling it immediately</strong>.</p>
<p>Example:</p>
<pre><code class="language-javascript">const person = {
  name: "Rahul"
};

function greet() {
  console.log("Hello " + this.name);
}

const greetRahul = greet.bind(person);

greetRahul();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Rahul
</code></pre>
<p>The function is stored and can be called later.</p>
<hr />
<h3>Difference Between <code>call</code>, <code>apply</code>, and <code>bind</code></h3>
<table>
<thead>
<tr>
<th>Method</th>
<th>When it runs</th>
<th>How arguments are passed</th>
</tr>
</thead>
<tbody><tr>
<td><code>call()</code></td>
<td>Runs immediately</td>
<td>Arguments passed individually</td>
</tr>
<tr>
<td><code>apply()</code></td>
<td>Runs immediately</td>
<td>Arguments passed as an array</td>
</tr>
<tr>
<td><code>bind()</code></td>
<td>Returns a new function</td>
<td>Arguments can be passed later</td>
</tr>
</tbody></table>
<p>Example comparison:</p>
<pre><code class="language-javascript">func.call(obj, a, b);
func.apply(obj, [a, b]);
const newFunc = func.bind(obj);
</code></pre>
<hr />
<h3>Practice Assignment</h3>
<p>Try the following exercise.</p>
<h3>1. Create an Object</h3>
<pre><code class="language-javascript">const student = {
  name: "Aman",
  showName() {
    console.log(this.name);
  }
};
</code></pre>
<hr />
<h3>2. Borrow the Method Using <code>call()</code></h3>
<pre><code class="language-javascript">const student2 = {
  name: "Riya"
};

student.showName.call(student2);
</code></pre>
<hr />
<h3>3. Use <code>apply()</code> with Arguments</h3>
<pre><code class="language-javascript">function introduce(city, country) {
  console.log(this.name + " from " + city + ", " + country);
}

introduce.apply(student2, ["Mumbai", "India"]);
</code></pre>
<hr />
<h3>4. Use <code>bind()</code></h3>
<pre><code class="language-javascript">const intro = introduce.bind(student2, "Delhi", "India");

intro();
</code></pre>
<hr />
<p>And now, you know what is the difference among <strong>call(), apply(), and bind()</strong> in <strong>JavaScript</strong></p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Function Declaration vs Function Expression: What’s the Difference?]]></title><description><![CDATA[Hey Everyone,
In this blog, we will learn about Function Declaration vs Function Expression in JavaScipt.
Functions are one of the most important concepts in JavaScript. They help us reuse code, organ]]></description><link>https://blogs.abhishekdogra.in/function-declaration-vs-function-expression-what-s-the-difference</link><guid isPermaLink="true">https://blogs.abhishekdogra.in/function-declaration-vs-function-expression-what-s-the-difference</guid><dc:creator><![CDATA[Abhi]]></dc:creator><pubDate>Sun, 15 Mar 2026 17:10:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6294933fd97f80b5091dcf59/1b1f556d-b84b-42b5-80a7-6f4c2e7b81e5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey Everyone,</p>
<p>In this blog, we will learn about Function Declaration vs Function Expression in JavaScipt.</p>
<p>Functions are one of the most important concepts in JavaScript. They help us <strong>reuse code</strong>, organize logic, and make programs easier to manage.</p>
<hr />
<h3>What Are Functions?</h3>
<p>A <strong>function</strong> is a reusable block of code designed to perform a specific task.</p>
<p>Instead of writing the same code again and again, we can wrap it inside a function and reuse it.</p>
<p>Example:</p>
<pre><code class="language-javascript">function add(a, b) {
  return a + b;
}

console.log(add(2, 3));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">5
</code></pre>
<p>Here, the function <strong>adds two numbers</strong> and returns the result.</p>
<p>Functions help keep code <strong>clean, organized, and reusable</strong>.</p>
<hr />
<h3>Function Declaration</h3>
<p>A <strong>function declaration</strong> defines a function using the <code>function</code> keyword followed by a function name.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">function functionName(parameters) {
  // code
}
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">function multiply(a, b) {
  return a * b;
}

console.log(multiply(4, 5));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">20
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>multiply</code> is the function name</p>
</li>
<li><p><code>a</code> and <code>b</code> are parameters</p>
</li>
<li><p>The function returns the product</p>
</li>
</ul>
<hr />
<h3>Function Expression</h3>
<p>A <strong>function expression</strong> means assigning a function to a variable.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">const functionName = function(parameters) {
  // code
};
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">20
</code></pre>
<p>The function works the same way, but here the function is <strong>stored inside a variable</strong>.</p>
<hr />
<h3>Declaration vs Expression (Side-by-Side)</h3>
<p>Function Declaration:</p>
<pre><code class="language-javascript">function greet(name) {
  return "Hello " + name;
}
</code></pre>
<p>Function Expression:</p>
<pre><code class="language-javascript">const greet = function(name) {
  return "Hello " + name;
};
</code></pre>
<p>Both functions behave similarly when called.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log(greet("Rahul"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Rahul
</code></pre>
<hr />
<h3>Key Differences</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Function Declaration</th>
<th>Function Expression</th>
</tr>
</thead>
<tbody><tr>
<td>Definition</td>
<td>Defined using <code>function</code> keyword</td>
<td>Stored inside a variable</td>
</tr>
<tr>
<td>Hoisting</td>
<td>Fully hoisted</td>
<td>Not fully hoisted</td>
</tr>
<tr>
<td>Usage</td>
<td>Can be called before definition</td>
<td>Must be defined before calling</td>
</tr>
<tr>
<td>Syntax</td>
<td><code>function add(){}</code></td>
<td><code>const add = function(){}</code></td>
</tr>
</tbody></table>
<hr />
<h3>Understanding Hoisting (Simple Explanation)</h3>
<p><strong>Hoisting</strong> means JavaScript moves certain declarations to the top during execution.</p>
<p>Let’s see an example.</p>
<h3>Function Declaration</h3>
<pre><code class="language-javascript">console.log(add(2,3));

function add(a,b){
  return a + b;
}
</code></pre>
<p>This works because <strong>function declarations are hoisted</strong>.</p>
<p>Output:</p>
<pre><code class="language-plaintext">5
</code></pre>
<hr />
<h3>Function Expression</h3>
<pre><code class="language-javascript">console.log(add(2,3));

const add = function(a,b){
  return a + b;
};
</code></pre>
<p>This will cause an error because the function <strong>is not available before it is defined</strong>.</p>
<p>Why?</p>
<p>Because the variable <code>add</code> is declared first but the function assignment happens later.</p>
<hr />
<h3>Simple Execution Flow</h3>
<p>Function Declaration:</p>
<pre><code class="language-plaintext">JS reads file
↓
Function is hoisted
↓
Function call works
</code></pre>
<p>Function Expression:</p>
<pre><code class="language-plaintext">JS reads file
↓
Variable created
↓
Function assigned later
↓
Calling before assignment causes error
</code></pre>
<hr />
<h3>When Should You Use Each?</h3>
<p>Use Function Declaration When</p>
<ul>
<li><p>You want a <strong>simple reusable function</strong></p>
</li>
<li><p>The function should be available <strong>anywhere in the file</strong></p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">function calculateTotal(price, tax) {
  return price + tax;
}
</code></pre>
<hr />
<h3>Use Function Expression When</h3>
<ul>
<li><p>You want to store a function in a variable</p>
</li>
<li><p>You want to pass functions as arguments</p>
</li>
<li><p>You want better control over scope</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const greet = function(name) {
  return "Hello " + name;
};
</code></pre>
<p>Many modern JavaScript patterns prefer expressions because they work well with <strong>callbacks and functional programming</strong>.</p>
<hr />
<h3>Practice Assignment</h3>
<p>Try this in your browser console.</p>
<h3>1. Function Declaration</h3>
<p>Write a function that multiplies two numbers.</p>
<pre><code class="language-javascript">function multiply(a, b) {
  return a * b;
}

console.log(multiply(3,4));
</code></pre>
<hr />
<h3>2. Function Expression</h3>
<p>Write the same logic using a function expression.</p>
<pre><code class="language-javascript">const multiplyExp = function(a, b) {
  return a * b;
};

console.log(multiplyExp(3,4));
</code></pre>
<hr />
<h3>3. Experiment With Hoisting</h3>
<p>Try calling both functions <strong>before defining them</strong>.</p>
<p>Observe:</p>
<ul>
<li><p>Function declaration works</p>
</li>
<li><p>Function expression throws an error</p>
</li>
</ul>
<p>This experiment helps you understand <strong>how JavaScript executes code</strong>.</p>
<hr />
<p>And now, you know what Function Declaration vs Function Expression is.</p>
<p>If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.</p>
<p>Thanks for reading, and see you in the next blog!</p>
<p>Peace ✌️ and Happy Learning!</p>
]]></content:encoded></item></channel></rss>