<?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[web-dev blogs]]></title><description><![CDATA[web-dev blogs]]></description><link>https://anilkambarweb.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1593680282896/kNC7E8IR4.png</url><title>web-dev blogs</title><link>https://anilkambarweb.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 09 Jun 2026 13:37:29 GMT</lastBuildDate><atom:link href="https://anilkambarweb.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The Node.js Event Loop: How JavaScript Does a Million Things at Once]]></title><description><![CDATA[If you’ve ever tried to cook a multi-course dinner alone, you know the struggle. You can’t chop onions and boil pasta at the exact same second. You have to switch back and forth.
Node.js faces a simil]]></description><link>https://anilkambarweb.hashnode.dev/the-node-js-event-loop-how-javascript-does-a-million-things-at-once</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/the-node-js-event-loop-how-javascript-does-a-million-things-at-once</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[single-threaded]]></category><category><![CDATA[non-blocking IO]]></category><category><![CDATA[callstack]]></category><category><![CDATA[Event Loop]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 03 May 2026 10:47:20 GMT</pubDate><content:encoded><![CDATA[<p>If you’ve ever tried to cook a multi-course dinner alone, you know the struggle. You can’t chop onions and boil pasta at the exact same second. You have to switch back and forth.</p>
<p>Node.js faces a similar problem. It is <strong>single-threaded</strong>, meaning it has only one "hand" to do work. Yet, it manages to handle thousands of users at once without breaking a sweat. How? The secret is a clever mechanism called the <strong>Event Loop</strong>.</p>
<h2><strong>Why Does Node.js Even Need an Event Loop?</strong></h2>
<p>Here's the big limitation: <strong>Node.js runs on a single thread.</strong> That means it can only do one thing at a time. If you've ever heard someone say "JavaScript is single-threaded," this is exactly what they mean.</p>
<p>Now, that sounds like a disaster waiting to happen. If one task takes too long — say, reading a file from disk or fetching data from a remote API — does everything else freeze and wait? In many languages and frameworks, yes, that's exactly what happens. This is called <strong>blocking</strong>.</p>
<blockquote>
<p><strong>🧠 Real-World Analogy</strong></p>
<p>Imagine a restaurant with just <strong>one waiter</strong>. If that waiter goes to the kitchen and waits there until the food is ready before taking another order — the whole restaurant grinds to a halt. Customers wait forever. That's blocking code. But what if the waiter takes your order, drops it at the kitchen window, and immediately moves on to the next table — checking back only when the food is ready? That's the <em>event loop</em>.</p>
</blockquote>
<p>Node.js solves the single-thread problem brilliantly: instead of waiting for slow tasks to finish, it <strong>delegates them, moves on, and comes back when they're done.</strong> The event loop is the system that makes this possible.</p>
<h2><strong>What Exactly Is the Event Loop?</strong></h2>
<p>Think of the event loop as a <strong>tireless task manager</strong> — a loop that runs continuously, asking one question over and over:</p>
<p><em><strong>"Is there anything new to do? If yes, do it. If no, keep watching."</strong></em></p>
<p>It constantly monitors two key areas: the <strong>Call Stack</strong> (where code is currently running) and the <strong>Task Queue</strong> (a waiting line of things ready to be run next). When the call stack is empty — meaning current work is done — the event loop picks the next task from the queue and pushes it onto the stack.</p>
<p>That's really it at its core. The elegance is in how simple the idea is, and how powerful the outcome becomes.</p>
<h2><strong>Call Stack, Task Queue &amp; Event Loop</strong></h2>
<p>Let's look at the three players in this system and how they work together:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/310840af-45b2-47cb-b1d4-25af38fba7d9.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>The Call Stack</strong></h3>
<p>The call stack is where your JavaScript code <em>actually runs</em>. When you call a function, it gets pushed onto the stack. When it finishes, it gets popped off. This happens synchronously — one thing at a time, top to bottom. Think of it like a stack of plates: you always work from the top.</p>
<h3><strong>The Task Queue (Callback Queue)</strong></h3>
<p>When an async operation completes — like a timer firing, or a file finishing loading — its callback function doesn't jump straight into the call stack. Instead, it <strong>waits patiently in the task queue</strong>. It's a first-in, first-out line. Fair, orderly, patient.</p>
<h3><strong>The Event Loop</strong></h3>
<p>The event loop's job is straightforward: it continuously watches the call stack. <strong>The moment the stack is empty</strong>, it takes the first callback from the task queue and pushes it onto the stack for execution. Rinse and repeat — forever.</p>
<h2><strong>How Async Operations Are Handled</strong></h2>
<p>Here's where it gets interesting. When Node.js encounters something slow — like reading a file, making an HTTP request, or querying a database — it doesn't sit and wait. Instead:</p>
<ol>
<li><p>Offload: The async task is handed off to the underlying system (libuv — Node's C++ library that handles I/O under the hood). Node doesn't deal with this itself.</p>
</li>
<li><p>Continue: Node keeps running your synchronous code without pause. The rest of your program doesn't freeze.</p>
</li>
<li><p>Notify: When the background task finishes, the callback you provided is placed into the Task Queue.</p>
</li>
<li><p>Execute: The event loop spots that the call stack is clear and moves the callback in for execution.</p>
</li>
</ol>
<blockquote>
<p><strong>🏪 Queue Analogy</strong></p>
<p>It's like ordering food online. You place your order (the async call), go about your day (synchronous code keeps running), and when the delivery driver arrives (task completes), you get a notification (callback in queue). Only then do you answer the door (event loop picks it up and runs the callback). You were never stuck waiting.</p>
</blockquote>
<p>This model is often described as <strong>non-blocking I/O</strong> — and it's the secret behind Node.js's ability to handle huge numbers of requests without needing multiple threads.</p>
<h2><strong>Event Loop Execution Cycle</strong></h2>
<p>Here's the event loop's cycle, visualized as a sequence of steps it repeats continuously:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/8d7b6a45-97d3-4d27-9a2e-2d09d4599a1f.png" alt="" style="display:block;margin:0 auto" />

<h2></h2>
<p><strong>Timers vs. I/O Callbacks</strong></p>
<p>Not all async operations are the same. At a high level, two types you'll encounter most often are <strong>Timers</strong> and <strong>I/O callbacks</strong>. Here's how they differ:</p>
<h3>Timers (setTimeout / setInterval)</h3>
<ul>
<li><p>Schedules code to run <strong>after a delay</strong></p>
</li>
<li><p>Timing is <strong>not exact</strong> — it runs <em>after at least</em> the given time</p>
</li>
<li><p>Commonly used for:</p>
<ul>
<li><p>Delays</p>
</li>
<li><p>Retries</p>
</li>
<li><p>Polling tasks</p>
</li>
</ul>
</li>
<li><p>Even <code>setTimeout(fn, 0)</code> runs <strong>asynchronously</strong>, not immediately</p>
</li>
</ul>
<h3>I/O (File / Network / Database)</h3>
<ul>
<li><p>Runs when an <strong>operation finishes</strong></p>
</li>
<li><p>Examples:</p>
<ul>
<li><p>Reading files</p>
</li>
<li><p>API/HTTP responses</p>
</li>
<li><p>Database queries</p>
</li>
</ul>
</li>
<li><p>Node.js sends these tasks to the <strong>OS or libuv thread pool</strong></p>
</li>
<li><p>The callback runs <strong>only when the result is ready</strong></p>
</li>
</ul>
<p>The key insight: <strong>both are non-blocking.</strong> When you call <code>fs.readFile()</code> or <code>setTimeout()</code>, Node registers the callback and moves on instantly. Neither one freezes the thread. The event loop brings the result back to you when it's ready.</p>
<h2><strong>How the Event Loop Enables Scalability</strong></h2>
<p>This is where everything clicks. Because Node.js never blocks the thread waiting for I/O, <strong>a single instance can handle thousands of concurrent connections</strong> with very low memory overhead.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/b6460c1b-bb86-4870-9f84-855e318fb951.png" alt="" style="display:block;margin:0 auto" />

<p>Compare this to a traditional multi-threaded server: each new connection spawns a new thread. Threads are expensive — they consume memory and switching between them has overhead. Node sidesteps this entirely by using just one thread and the event loop.</p>
<blockquote>
<p><em>This is why companies like Netflix, LinkedIn, and PayPal moved to Node.js — they found it handled massive concurrency with far fewer resources.</em></p>
</blockquote>
<p>Of course, this strength comes with one important caveat: <strong>don't block the event loop.</strong> If you write code that runs a heavy computation synchronously (like crunching millions of numbers in a loop), it will freeze the entire thread and make your server unresponsive. For CPU-heavy work, Node offers Worker Threads — but that's a story for another day.</p>
<h2><strong>The Mental Model to Remember</strong></h2>
<p>The Node.js event loop can be summed up in one sentence: <strong>do the work, delegate the waiting, come back when ready.</strong></p>
<p>Your code runs synchronously in the call stack. Slow operations are handed off. Their results queue up. The event loop bridges the queue and the stack — continuously, efficiently, without ever blocking.</p>
<p>Master this model and everything about Node.js async programming — Promises, async/await, streams — starts to make intuitive sense.  </p>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[REST API Design Made Simple with Express.js]]></title><description><![CDATA[If you’ve ever wondered how your phone gets the latest posts from Instagram or how a website saves your profile information, you’re looking at the work of an API.
Specifically, most modern apps use so]]></description><link>https://anilkambarweb.hashnode.dev/rest-api-design-made-simple-with-express-js</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/rest-api-design-made-simple-with-express-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backendjs]]></category><category><![CDATA[httpmethods]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 03 May 2026 09:04:59 GMT</pubDate><content:encoded><![CDATA[<p>If you’ve ever wondered how your phone gets the latest posts from Instagram or how a website saves your profile information, you’re looking at the work of an <strong>API</strong>.</p>
<p>Specifically, most modern apps use something called a <strong>REST API</strong>. While it sounds technical, the concept is as simple as ordering food at a restaurant. Let’s break it down using <strong>Express.js</strong>, the most popular tool for building these in the world of JavaScript.</p>
<h2><strong>What is a REST API?</strong></h2>
<p>Imagine you're at a restaurant. You (the <strong>client</strong>) look at a menu and tell the waiter (the <strong>API</strong>) what you want. The waiter goes to the kitchen (the <strong>server</strong>), grabs your food, and brings it back. You never need to go into the kitchen yourself.</p>
<p>A <strong>REST API</strong> works the same way. It's a set of rules that lets two applications talk to each other — your browser or app asks for something, and the server responds with data.</p>
<blockquote>
<p><strong>💡 Simple Definition</strong></p>
<p><strong>REST</strong> stands for <em>Representational State Transfer</em>. It's just a style of building APIs that is clean, predictable, and easy to understand. When an API follows REST rules, developers know exactly how to use it — no guesswork.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/bd8cdd5d-d3e0-48eb-839f-5ebc1c0622d8.png" alt="" style="display:block;margin:0 auto" />

<p>The key rules REST follows are: use <strong>URLs to identify things</strong>, use <strong>HTTP methods to say what to do</strong>, and <strong>return data in JSON</strong> format.</p>
<h2><strong>Resources in REST Architecture</strong></h2>
<p>In REST, everything is a <strong>resource</strong>. A resource is simply a "thing" your API can work with — like a user, a product, an order, or a post.</p>
<p>Resources are identified by <strong>URLs</strong> (also called endpoints). Think of a URL as a home address for your data.</p>
<p><strong>Resource URL Examples</strong></p>
<p>A <strong>/users</strong> resource might represent all your users. When you go to:</p>
<ul>
<li><p><code>/users</code>  →  All users</p>
</li>
<li><p><code>/users/42</code>  →  The user with ID 42</p>
</li>
<li><p><code>/users/42/posts</code>  →  All posts by user 42</p>
</li>
</ul>
<blockquote>
<p><strong>Golden Rule:</strong></p>
<p>Always use <strong>nouns</strong> (things) in URLs, never verbs (actions). The action is expressed by the HTTP method instead. So it's <code>/users</code> — never <code>/getUsers</code> or <code>/deleteUser</code>.</p>
</blockquote>
<h2><strong>HTTP Methods</strong></h2>
<p>Once you have a resource URL, you need to tell the server <em>what to do</em> with it. That's what <strong>HTTP methods</strong> are for. There are four main ones, and they map directly to four database operations called <strong>CRUD</strong>.</p>
<p><strong>CRUD vs HTTP Methods Mapping</strong></p>
<table>
<thead>
<tr>
<th><strong>CRUD Operation</strong></th>
<th><strong>HTTP Method</strong></th>
<th><strong>What it does</strong></th>
<th><strong>Example URL</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Create</strong></td>
<td><strong>POST</strong></td>
<td>Add new data</td>
<td>POST /users</td>
</tr>
<tr>
<td><strong>Read</strong></td>
<td><strong>GET</strong></td>
<td>Fetch existing data</td>
<td>GET /users</td>
</tr>
<tr>
<td><strong>Update</strong></td>
<td><strong>PUT</strong></td>
<td>Replace existing data</td>
<td>PUT /users/1</td>
</tr>
<tr>
<td><strong>Delete</strong></td>
<td><strong>DELETE</strong></td>
<td>Remove data</td>
<td>DELETE /users/1</td>
</tr>
</tbody></table>
<h3><strong>GET — Fetching Data</strong></h3>
<p><strong>GET</strong> is the most common method. It's like reading a book — you look at the data, but you don't change anything. Safe to call as many times as you want.</p>
<pre><code class="language-javascript">// GET all users
const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]

app.get('/users', (req, res) =&gt; {
  res.json(users);
});

// GET a single user by ID
app.get('/users/:id', (req, res) =&gt; {
  const userId = Number(req.params.id);
  const user = users.findIndex(user =&gt; user.id === userId)
  res.json({ user });
});
</code></pre>
<h3><strong>POST — Creating Data</strong></h3>
<p><strong>POST</strong> sends new data to the server to be created. Think of it like filling out a form and hitting Submit.</p>
<pre><code class="language-javascript">// POST — Create a new user
app.post('/users', (req, res) =&gt; {
  const { name, email } = req.body;

  // Basic validation
  if (!name || !email) {
    return res.status(400).json({ message: "Name and email are required" });
  }

  // Create new user
  const newUser = {
    id: users.length + 1,
    name,
    email
  };

  // 🔥 Save to array
  users.push(newUser);

  res.status(201).json(newUser);
});
</code></pre>
<h3><strong>PUT — Updating Data</strong></h3>
<p><strong>PUT</strong> replaces an existing item completely. You're saying "replace everything about this user with what I'm sending now."</p>
<pre><code class="language-javascript">// PUT — Update a user
app.put('/users/:id', (req, res) =&gt; {
  const { name, email } = req.body;
  const userId = Number(req.params.id);

  const index = users.findIndex(user =&gt; user.id === userId);

  if (index === -1) {
    return res.status(404).json({ message: "User not found" });
  }

  // 🔥 Update the actual data
  users[index] = {
    ...users[index],  // keep existing fields
    name,
    email
  };

  res.status(200).json(users[index]);
});
</code></pre>
<h3><strong>DELETE — Removing Data</strong></h3>
<p><strong>DELETE</strong> removes an item from the server. Simple and permanent — like tossing something in the bin.</p>
<pre><code class="language-javascript">app.delete('/users/:id', (req, res) =&gt; {
  const userId = Number(req.params.id);

  const index = users.findIndex(user =&gt; user.id === userId);

  if (index === -1) {
    return res.status(404).json({ message: "User not found" });
  }

  // 🔥 Remove user from array
  users.splice(index, 1);

  // 204 = success, no content
  res.status(204).send();
});
</code></pre>
<h2><strong>Status Codes Basics</strong></h2>
<p>Every time your server responds, it sends a <strong>status code</strong> — a 3-digit number that tells the client what happened. Think of them like emoji reactions: the server is telling you "thumbs up", "not found", or "something broke".</p>
<blockquote>
<p><strong>💡 Analogy</strong></p>
<p>Status codes are like delivery status notifications — <strong>200</strong> is "Delivered!", <strong>404</strong> is "Address not found", and <strong>500</strong> is "Delivery truck broke down."</p>
</blockquote>
<h3>Common Status Codes You Must Know</h3>
<p><strong>✅ Success Codes (2xx)</strong></p>
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><strong>200</strong></td>
<td>OK</td>
<td>Request successful, data returned</td>
</tr>
<tr>
<td><strong>201</strong></td>
<td>Created</td>
<td>New resource created successfully</td>
</tr>
<tr>
<td><strong>204</strong></td>
<td>No Content</td>
<td>Success, but nothing to return</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">GET /users → 200 OK
POST /users → 201 Created
DELETE /users/1 → 204 No Content
</code></pre>
<p><strong>❌ Client Errors (4xx)</strong></p>
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><strong>400</strong></td>
<td>Bad Request</td>
<td>Invalid data sent</td>
</tr>
<tr>
<td><strong>401</strong></td>
<td>Unauthorized</td>
<td>Login required</td>
</tr>
<tr>
<td><strong>403</strong></td>
<td>Forbidden</td>
<td>No permission</td>
</tr>
<tr>
<td><strong>404</strong></td>
<td>Not Found</td>
<td>Resource doesn’t exist</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">GET /users/999 → 404 Not Found
POST /users (missing name) → 400 Bad Request
</code></pre>
<p><strong>💥 Server Errors (5xx)</strong></p>
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><strong>500</strong></td>
<td>Internal Server Error</td>
<td>Something broke on server</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">GET /users → 500 Server Error (bug in code)
</code></pre>
<h2><strong>Designing Routes Using REST Principles</strong></h2>
<p>A <strong>route</strong> is a URL + HTTP method combination. Great REST routes are clean, consistent, and instantly understandable to any developer.</p>
<h4><strong>REST Route Checklist</strong></h4>
<ul>
<li><p>Use <strong>plural nouns</strong> for collections: <code>/users</code>, not <code>/user</code></p>
</li>
<li><p>Use <strong>IDs in the path</strong> for single items: <code>/users/5</code></p>
</li>
<li><p><strong>Never put verbs</strong> in routes: ❌ <code>/getUser</code>, ❌ <code>/createUser</code></p>
</li>
<li><p>Keep them <strong>lowercase</strong> and use <strong>hyphens</strong> for multi-word resources: <code>/blog-posts</code></p>
</li>
</ul>
<h3><strong>Good Routes vs ❌ Bad Routes</strong></h3>
<table>
<thead>
<tr>
<th><strong>✅ Good</strong></th>
<th><strong>❌ Bad</strong></th>
<th><strong>Why it matters</strong></th>
</tr>
</thead>
<tbody><tr>
<td>GET /users</td>
<td>GET /getUsers</td>
<td>Verb belongs in the HTTP method, not the URL</td>
</tr>
<tr>
<td>POST /users</td>
<td>POST /createUser</td>
<td>POST already means "create"</td>
</tr>
<tr>
<td>DELETE /users/5</td>
<td>GET /deleteUser?id=5</td>
<td>Use DELETE method + ID in path</td>
</tr>
<tr>
<td>GET /blog-posts</td>
<td>GET /BlogPosts</td>
<td>URLs should be lowercase, hyphens for spaces</td>
</tr>
</tbody></table>
<h2><strong>Full Example: Users API in Express.js</strong></h2>
<p>Let's put it all together. Here's a complete, working Express.js REST API for a <strong>Users</strong> resource. This is what a real beginner-level API looks like:</p>
<p><strong>👥 Users API — All Routes at a Glance</strong></p>
<table>
<thead>
<tr>
<th><strong>Method</strong></th>
<th><strong>Route</strong></th>
<th><strong>What it does</strong></th>
<th><strong>Status Code</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>GET</strong></td>
<td>/users</td>
<td>Get all users</td>
<td>200 OK</td>
</tr>
<tr>
<td><strong>GET</strong></td>
<td>/users/:id</td>
<td>Get one user by ID</td>
<td>200 OK</td>
</tr>
<tr>
<td><strong>POST</strong></td>
<td>/users</td>
<td>Create a new user</td>
<td>201 Created</td>
</tr>
<tr>
<td><strong>PUT</strong></td>
<td>/users/:id</td>
<td>Update existing user</td>
<td>200 OK</td>
</tr>
<tr>
<td><strong>DELETE</strong></td>
<td>/users/:id</td>
<td>Delete a user</td>
<td>204 No Content</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">const express = require('express');
const app = express();

app.use(express.json()); // Parse JSON request bodies

// Fake in-memory "database"
let users = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob',   email: 'bob@example.com' },
];

// ─────────────────────────────────────────
// GET /users — Fetch all users
// ─────────────────────────────────────────
app.get('/users', (req, res) =&gt; {
  res.status(200).json(users);
});

// ─────────────────────────────────────────
// GET /users/:id — Fetch one user
// ─────────────────────────────────────────
app.get('/users/:id', (req, res) =&gt; {
  const user = users.find(u =&gt; u.id === +req.params.id);
  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }
  res.status(200).json(user);
});

// ─────────────────────────────────────────
// POST /users — Create a new user
// ─────────────────────────────────────────
app.post('/users', (req, res) =&gt; {
  const { name, email } = req.body;
  const newUser = { id: users.length + 1, name, email };
  users.push(newUser);
  res.status(201).json(newUser);
});

// ─────────────────────────────────────────
// PUT /users/:id — Update a user
// ─────────────────────────────────────────
app.put('/users/:id', (req, res) =&gt; {
  const index = users.findIndex(u =&gt; u.id === +req.params.id);
  if (index === -1) {
    return res.status(404).json({ error: 'User not found' });
  }
  users[index] = { ...users[index], ...req.body };
  res.status(200).json(users[index]);
});

// ─────────────────────────────────────────
// DELETE /users/:id — Delete a user
// ─────────────────────────────────────────
app.delete('/users/:id', (req, res) =&gt; {
  users = users.filter(u =&gt; u.id !== +req.params.id);
  res.status(204).send();
});

// ─────────────────────────────────────────
// Start server
// ─────────────────────────────────────────
app.listen(3000, () =&gt; {
  console.log('Server running on http://localhost:3000');
});
</code></pre>
<blockquote>
<p><strong>🎉 What You Just Built</strong></p>
<p>That's a fully working REST API! It handles <strong>Create</strong>, <strong>Read</strong>, <strong>Update</strong>, and <strong>Delete</strong> for users — follows clean REST conventions — and returns the right status codes. This is the foundation every backend developer needs to know.</p>
</blockquote>
<h3><strong>Run it Yourself in 3 Steps</strong></h3>
<pre><code class="language-plaintext"># Step 1: Create a project and install Express
mkdir my-api &amp;&amp; cd my-api
npm init -y
npm install express

# Step 2: Create your file and paste the code above
touch users-api.js

# Step 3: Run the server
node users-api.js
# → Server running on http://localhost:3000
</code></pre>
<p>Now open your browser or a tool like <strong>Postman/requestkit</strong> and visit <a href="http://localhost:3000/users"><code>http://localhost:3000/users</code></a> — you'll see your users list in JSON!  </p>
<h2><strong>What You Learned</strong></h2>
<p>🌐<strong>REST = Rules:</strong> A style that makes APIs predictable and easy to use by any developer.</p>
<p>📦<strong>Resources = URLs:</strong> Everything your API exposes is a named resource with its own URL.</p>
<p>🔧<strong>Methods = Actions:</strong> GET, POST, PUT, DELETE tell the server what to do with the resource.</p>
<p>📊<strong>Status Codes = Replies:</strong> 200s = success, 400s = client error, 500s = server error.</p>
<h2><strong><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></strong></h2>
]]></content:encoded></item><item><title><![CDATA[Node.js 101: Stop Waiting, Start Doing (Blocking vs. Non-Blocking)]]></title><description><![CDATA[If you’re just starting with Node.js, you’ve likely heard that it’s "fast" and "scalable." But why? The secret sauce lies in how it handles tasks. Most traditional programming languages work like a si]]></description><link>https://anilkambarweb.hashnode.dev/node-js-101-stop-waiting-start-doing-blocking-vs-non-blocking</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/node-js-101-stop-waiting-start-doing-blocking-vs-non-blocking</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[blocking code Node.js]]></category><category><![CDATA[non-blocking code Node.js]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sat, 02 May 2026 19:51:27 GMT</pubDate><content:encoded><![CDATA[<p>If you’re just starting with Node.js, you’ve likely heard that it’s "fast" and "scalable." But why? The secret sauce lies in how it handles tasks. Most traditional programming languages work like a single-lane road, while Node.js works more like a high-speed multi-tasking machine.</p>
<p>Let’s break down the difference between <strong>Blocking</strong> and <strong>Non-Blocking</strong> code so you can write better, faster applications.</p>
<h2><strong>Imagine a Coffee Shop</strong></h2>
<p><strong>☕ Blocking Cashier</strong></p>
<p>This cashier takes your order, then <strong>stands frozen</strong> at the counter staring at the espresso machine until your coffee is ready — maybe 3 minutes. No one else can order. The whole queue waits. The cashier is <em>blocked</em>.</p>
<p><strong>☕ Non-Blocking Cashier</strong></p>
<p>This cashier takes your order, tells the barista to make it, and <strong>immediately turns to the next customer</strong>. When your coffee is done, the barista calls your name. Nobody waits. The cashier is <em>non-blocking</em>.</p>
<p>Node.js is designed to be that <em>second cashier</em> — always ready to handle the next request without standing around waiting.</p>
<h2><strong>What Does "Blocking" Mean?</strong></h2>
<p>Blocking code means your program <strong>stops and waits</strong> for an operation to finish before it moves on to the next line. During that wait, nothing else can happen in your program.</p>
<p>These slow operations are usually things like: reading a file from disk, querying a database, or fetching data from an API. They all take time — and blocking code just sits there waiting.</p>
<p>Here's what blocking file reading looks like in Node.js:</p>
<pre><code class="language-javascript">const fs = require('fs');

// ❌ Program STOPS here until the file is fully read
const data = fs.readFileSync('bigfile.txt', 'utf8');

console.log(data);            // runs AFTER file is read
console.log('Done!');         // runs AFTER that

// If 1000 users hit your server, each waits in line 😬
</code></pre>
<p>The suffix <code>Sync</code> in <code>readFileSync</code> is your warning sign — it means synchronous, which means <em>blocking</em>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/fa5717e1-e4d6-46e3-95a6-b3ebf56546e9.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>What Does "Non-Blocking" Mean?</strong></h2>
<p>Non-blocking code means your program <strong>starts a task and moves on immediately</strong> — it doesn't wait. When the task finishes, a <em>callback</em> (or a Promise) is triggered to handle the result.</p>
<p>This is the heart of how Node.js works. Node uses a <strong>single thread</strong> (one worker), and it can only do one thing at a time — but by not waiting around, it can juggle thousands of requests efficiently.</p>
<pre><code class="language-javascript">const fs = require('fs');

// ✅ Node starts reading, then moves on IMMEDIATELY
fs.readFile('bigfile.txt', 'utf8', (err, data) =&gt; {
  if (err) throw err;
  console.log(data);       // runs when file is ready
});

// ✅ This runs RIGHT NOW, without waiting!
console.log('Handling other requests...');

// Output order:
// → "Handling other requests..."
// → (file contents, printed later)
</code></pre>
<blockquote>
<p>💡</p>
<p>The <strong>callback function</strong> <code>(err, data) =&gt; { ... }</code> is like leaving your phone number at the coffee shop. You walk away, and when your order is ready — they call you back!</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/dc2f603e-50bf-4c92-8b58-fce5e087f0b8.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Why Blocking Slows Your Server</strong></h2>
<p>Node.js runs on a <strong>single thread</strong>. That means it has one "worker". If that worker is blocked waiting for a file to load, it literally cannot answer any other request — not even a tiny "ping" request.</p>
<h3><strong>🔴 Blocking Server</strong></h3>
<ul>
<li><p>1 user blocks the entire server</p>
</li>
<li><p>Other users must queue up and wait</p>
</li>
<li><p>10 users = 10× slower response times</p>
</li>
<li><p>100 users? The server feels crashed</p>
</li>
<li><p>CPU idles while waiting on I/O</p>
</li>
</ul>
<h3><strong>🟢 Non-Blocking Server</strong></h3>
<ul>
<li><p>1 user's slow task doesn't block others</p>
</li>
<li><p>Requests are processed in parallel</p>
</li>
<li><p>10,000 concurrent users is feasible</p>
</li>
<li><p>CPU is always doing useful work</p>
</li>
<li><p>This is why Node.js was built!</p>
</li>
</ul>
<p>This is the core reason Node.js became so popular for web servers. It was specifically designed to handle thousands of simultaneous connections without needing thousands of threads.</p>
<h2><strong>Three Ways to Write Async Code</strong></h2>
<p>Over time, JavaScript evolved three different styles for writing non-blocking code. Think of them as three generations of the same idea:</p>
<ol>
<li><p><strong>Callbacks</strong> — The original way. You pass a function as an argument, and it gets called when the task is done. Simple, but can lead to deeply nested "callback hell."</p>
</li>
<li><p><strong>Promises</strong> — A cleaner approach introduced in ES6. You chain <code>.then()</code> and <code>.catch()</code> to handle results and errors.</p>
</li>
<li><p><strong>async / await</strong> — The modern standard. Looks almost like synchronous code but is fully non-blocking under the hood. This is what most developers use today.</p>
</li>
</ol>
<pre><code class="language-javascript">// ──────────────────────────────────────────
// 1. CALLBACK STYLE (old school)
// ──────────────────────────────────────────
fs.readFile('data.txt', 'utf8', function(err, data) {
  if (err) throw err;
  console.log(data);
});

// ──────────────────────────────────────────
// 2. PROMISE STYLE
// ──────────────────────────────────────────
fs.promises.readFile('data.txt', 'utf8')
  .then(data =&gt; console.log(data))
  .catch(err =&gt; console.error(err));

// ──────────────────────────────────────────
// 3. ASYNC/AWAIT STYLE (recommended ✅)
// ──────────────────────────────────────────
async function readMyFile() {
  try {
    const data = await fs.promises.readFile('data.txt', 'utf8');
    console.log(data);      // waits here WITHOUT blocking the server
  } catch (err) {
    console.error(err);
  }
}
readMyFile();
</code></pre>
<h2><strong>File Reads &amp; Database Calls</strong></h2>
<p>The two most common places you'll encounter blocking vs non-blocking decisions are <strong>file system operations</strong> and <strong>database queries(Database is always is a another continent)</strong>. Both are "slow" operations — they involve I/O (Input/Output), meaning data has to travel between your program and some storage system.</p>
<pre><code class="language-javascript">const express = require('express');
const fs      = require('fs');
const app     = express();

// ❌ BAD: Blocking route — holds up everyone else
app.get('/bad', (req, res) =&gt; {
  const data = fs.readFileSync('big-report.txt', 'utf8');
  res.send(data);
  // All other requests WAIT while this file is being read
});

// ✅ GOOD: Non-blocking route — server stays responsive
app.get('/good', async (req, res) =&gt; {
  const data = await fs.promises.readFile('big-report.txt', 'utf8');
  res.send(data);
  // While waiting, server handles other requests normally 🎉
});

app.listen(3000);
</code></pre>
<h3>Database Query</h3>
<pre><code class="language-javascript">// Simulated database call (same pattern works for MongoDB, MySQL, etc.)
async function getUserFromDB(userId) {
  // DB query can take 100ms–2s depending on load
  const user = await db.query(
    `SELECT * FROM users WHERE id = ?`, [userId]
  );
  return user;
}

app.get('/user/:id', async (req, res) =&gt; {
  try {
    const user = await getUserFromDB(req.params.id);
    res.json(user);     // ✅ other routes still work during await
  } catch (err) {
    res.status(500).json({ error: 'Something went wrong' });
  }
}):
</code></pre>
<blockquote>
<p>🗝️<strong>Rule of thumb:</strong> If you see <code>Sync</code> at the end of any Node.js function name, it's blocking. Avoid it in server code. It's only acceptable in startup scripts that run once before the server begins listening.</p>
</blockquote>
<h2><strong>What You've Learned</strong></h2>
<p>Here's everything from today, distilled into five key takeaways:</p>
<ol>
<li><p><strong>Blocking code waits.</strong> The program freezes on one task and all other tasks queue up behind it.</p>
</li>
<li><p><strong>Non-blocking code delegates.</strong> The program hands off slow work to the OS/system and moves on immediately.</p>
</li>
<li><p><strong>Node.js is single-threaded.</strong> This makes non-blocking patterns not just nice to have, but <em>essential</em> for a responsive server.</p>
</li>
<li><p><strong>File I/O and DB queries are the usual suspects.</strong> Always reach for the async version of these operations.</p>
</li>
<li><p><strong>Use async/await.</strong> It's the cleanest modern syntax and keeps your code readable while staying non-blocking.</p>
</li>
</ol>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg<br /></mark></h2>
]]></content:encoded></item><item><title><![CDATA[Setting Up Your First Node.js Application]]></title><description><![CDATA[Before we dive in — what is Node.js, exactly? Node.js is a tool that lets you run JavaScript code outside of a web browser, directly on your computer or a server. Normally, JavaScript only runs inside]]></description><link>https://anilkambarweb.hashnode.dev/setting-up-your-first-node-js-application</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/setting-up-your-first-node-js-application</guid><category><![CDATA[setup Node.js step by step]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sat, 02 May 2026 08:27:24 GMT</pubDate><content:encoded><![CDATA[<p>Before we dive in — <strong>what is Node.js, exactly?</strong> Node.js is a tool that lets you run JavaScript code outside of a web browser, directly on your computer or a server. Normally, JavaScript only runs inside browsers like Chrome or Firefox. Node.js changes that.</p>
<p>Think of it this way: if JavaScript is water, Node.js is the pipe system that lets that water flow anywhere — not just through a browser faucet. It's used by millions of developers to build web servers, command-line tools, APIs, and much more.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/3684560f-ea24-446f-915e-f459ae80eaa0.png" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p>Don't worry about V8 or libuv for now. Just know that Node.js takes your code, understands it, and produces a result — similar to how a calculator takes a sum and gives you the answer.</p>
</blockquote>
<h2><strong>Installing Node.js</strong></h2>
<p>The first thing you need to do is download and install Node.js. The good news is the process is the same regardless of your operating system — Windows, macOS, or Linux.</p>
<ol>
<li><p><strong>Go to the official Node.js website</strong><br />Open your browser and visit <a href="https://nodejs.org/en"><strong>nodejs.org</strong></a>. You'll see two versions — LTS (Long Term Support) and Current.</p>
</li>
<li><p><strong>Download the LTS version</strong><br /><strong>Always choose LTS as a beginner.</strong> It's the stable, well-tested version. "Current" has newer features but may have bugs.</p>
</li>
<li><p><strong>Run the installer</strong><br />Open the downloaded file and follow the setup wizard. Click "Next" through all the steps and accept the license. The installer handles everything automatically.</p>
</li>
<li><p><strong>Restart your terminal (if open)</strong><br />If you already had a terminal or command prompt open, close and re-open it so it picks up the newly installed Node.js.</p>
</li>
</ol>
<blockquote>
<p>When you install Node.js, it automatically installs <strong>npm</strong> (Node Package Manager) too. npm is like an app store for Node.js packages. We won't use it in this article, but it's good to know it's there.</p>
</blockquote>
<h2><strong>Checking the Installation</strong></h2>
<p>After installation, we need to <strong>verify that Node.js is correctly installed</strong> using the terminal (also called Command Prompt on Windows, or Terminal on Mac/Linux). Think of the terminal as a text-based way to talk to your computer.</p>
<p>How to open your terminal:</p>
<p>🪟<strong>Windows</strong><br />Press <code>Win + R</code>, type <code>cmd</code>, and press Enter. Or search for "Command Prompt" or "PowerShell".</p>
<p>🍎<strong>macOS</strong><br />Press <code>Cmd + Space</code>, type <code>Terminal</code>, and press Enter.</p>
<p>🐧<strong>Linux</strong><br />Press <code>Ctrl + Alt + T</code> or search for "Terminal" in your apps.</p>
<p>Once your terminal is open, type these two commands to check the versions:</p>
<pre><code class="language-shell">$ node --version
v20.11.0   // Your version number will appear here

$ npm --version
10.2.4    // npm version (installed alongside Node.js)
</code></pre>
<blockquote>
<p>If you see version numbers like <code>v20.x.x</code>, congratulations — Node.js is installed correctly! If you see an error like "command not found", try restarting your terminal or re-running the installer.</p>
</blockquote>
<h2><strong>Understanding Node REPL</strong></h2>
<p>Before writing files, let's explore something fun — the <strong>Node.js REPL</strong>. REPL stands for <strong>Read–Eval–Print Loop</strong>. That's a mouthful, but the idea is simple:</p>
<p>📖<strong>Read:</strong> It reads what you type in.</p>
<p>⚙️<strong>Eval:</strong> It evaluates (runs) your code.</p>
<p>🖨️<strong>Print:</strong> It prints the result back to you.</p>
<p>🔁<strong>Loop:</strong> It keeps going until you quit.</p>
<p>The REPL is like a live JavaScript playground. It's perfect for quickly testing small pieces of code without creating a file. To enter the REPL, just type <code>node</code> and press Enter:</p>
<pre><code class="language-shell">$ node
Welcome to Node.js v20.11.0.
Type ".help" for more information.
&gt; 
</code></pre>
<p>Now you'll see the <code>&gt;</code> prompt. That means Node is waiting for your input. Try these commands:</p>
<pre><code class="language-shell">&gt; 2 + 2
4

&gt; "Hello" + " " + "World"
'Hello World'

&gt; let name = "Node"
undefined

&gt; console.log("Hello from " + name)
Hello from Node
undefined

&gt; 
</code></pre>
<p>Notice that after <code>let name = "Node"</code>, the REPL prints <code>undefined</code>. That's perfectly normal — variable declarations don't return a value. To <strong>exit the REPL</strong>, press <code>Ctrl + C</code> twice, or type <code>.exit</code> and press Enter.</p>
<blockquote>
<p>⚠️</p>
<p>The REPL is only for quick experiments — your code is <strong>not saved</strong> here. For real programs, we write files (which we'll do next).</p>
</blockquote>
<h2><strong>Creating Your First JS File</strong></h2>
<p>Now let's write a real script. A script is just a text file with a <code>.js</code> extension containing JavaScript code. You can use any text editor — Notepad, VS Code, Sublime Text, etc. For beginners, we recommend <strong>VS Code</strong> (free, at <a href="http://code.visualstudio.com">code.visualstudio.com</a>), but any editor works.</p>
<ol>
<li><p><strong>Create a new folder:</strong> Create a folder anywhere on your computer, like <code>my-first-node-app</code> on your Desktop.</p>
</li>
<li><p><strong>Create a new file:</strong> Inside that folder, create a new file and name it <code>app.js</code>. The <code>.js</code> extension tells Node that this is a JavaScript file.</p>
</li>
<li><p><strong>Write your first code:</strong> Open <code>app.js</code> in your text editor and type the following:</p>
</li>
</ol>
<pre><code class="language-shell">// My very first Node.js script!

console.log("Hello! I am running inside Node.js!");

console.log("Today is: " + new Date().toDateString());

console.log("2 + 2 equals: " + (2 + 2));
</code></pre>
<p>Let's break down what each line does:</p>
<p>💬<code>// My very first Node.js script!</code></p>
<p>Lines starting with <code>//</code> are <strong>comments</strong>. Node.js completely ignores them. They're just notes for you (or other developers) to read.</p>
<p>🖨️<code>console.log(...)</code></p>
<p>This is the command to <strong>print something to the terminal</strong>. Whatever you put in the parentheses gets displayed. It's the most-used command in all of JavaScript.</p>
<p>Save the file. That's your first Node.js program! Now let's run it.</p>
<h2><strong>Running Your Script</strong></h2>
<p>Now let's execute the file we just created. Open your terminal and <strong>navigate to the folder</strong> where you saved <code>app.js</code>.</p>
<blockquote>
<p>📁 To navigate in the terminal, use the <code>cd</code> command (which stands for "change directory"). For example: <code>cd Desktop/my-first-node-app</code></p>
</blockquote>
<p>Once you're inside the correct folder, run your script with the <code>node</code> command followed by the filename:</p>
<pre><code class="language-shell">$ node app.js

Hello! I am running inside Node.js!
Today is: Sat May 02 2026
2 + 2 equals: 4
</code></pre>
<p>You should see all three lines printed in your terminal. 🎉 <strong>You just ran your first Node.js program!</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/2ac37639-0ae0-4dc3-b3b2-3ac6cd8e1130.png" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p>💡Every time you change <code>app.js</code> and want to see the updated output, just run <code>node app.js</code> again. Node doesn't auto-refresh — you manually run it each time.</p>
</blockquote>
<h2><strong>Writing a Hello World HTTP Server</strong></h2>
<p>Here's where things get exciting. Node.js has a built-in module called <code>http</code> that lets you create a web server — with <strong>zero additional tools or frameworks</strong>. Let's write one now.</p>
<p><strong>What is an HTTP server?</strong> When you visit a website, your browser sends a request to a server, and the server sends back a response (like an HTML page). We're going to build that server ourselves.</p>
<p>Create a new file in the same folder, named <code>server.js</code>, and type the following:</p>
<pre><code class="language-javascript">// Step 1: Import the built-in 'http' module
const http = require('http');

// Step 2: Define what HOST and PORT to use
const HOST = 'localhost';   // "localhost" means your own computer
const PORT = 3000;           // Port 3000 is a popular choice for development

// Step 3: Create the server
// Every time someone visits our URL, this function runs
const server = http.createServer(function(request, response) {

  // Tell the browser: "Everything is OK, and the content is plain text"
  response.writeHead(200, { 'Content-Type': 'text/plain' });

  // Send back our message and end the response
  response.end('Hello World! My first Node.js server is running!\n');

});

// Step 4: Start the server and listen for requests
server.listen(PORT, HOST, function() {
  console.log(`✅ Server is running! Visit: http://\({HOST}:\){PORT}`);
});
</code></pre>
<p>Now let's understand each part:</p>
<ol>
<li><p><code>const http = require('http')</code><br />This loads Node's built-in <code>http</code> module. Think of modules as toolboxes — <code>require()</code> opens the toolbox and puts it in a variable.</p>
</li>
<li><p><code>localhost</code> <strong>and</strong> <code>PORT 3000</code><br /><code>localhost</code> is a special address that means "this computer". Port <code>3000</code> is like a door number — it tells your computer which program to send requests to. (Your browser uses port 80/443 by default for websites.)</p>
</li>
<li><p><code>http.createServer(function(request, response) {...})</code><br />This creates a server. The function inside runs every time a browser visits our URL. <code>request</code> = what the browser asked for. <code>response</code> = what we send back.</p>
</li>
<li><p><code>response.writeHead(200, ...)</code><br />The number <code>200</code> is an HTTP status code meaning "Success / OK". You've probably seen <code>404</code> which means "Not Found". This is the same system.</p>
</li>
<li><p><code>server.listen(PORT, HOST, ...)</code><br />This starts the server and makes it begin "listening" for incoming requests. The callback function runs once when the server successfully starts up.</p>
</li>
</ol>
<p><strong>Now run the server in your terminal:</strong></p>
<pre><code class="language-shell">$ node server.js

✅ Server is running! Visit: http://localhost:3000
</code></pre>
<p>The terminal will appear to "hang" or "freeze" — that's intentional! <strong>Your server is now actively waiting</strong> for requests. It's alive and running.</p>
<blockquote>
<p>🌐 Open your web browser and go to <a href="http://localhost:3000"><code>http://localhost:3000</code></a>. You should see the text: <strong>"Hello World! My first Node.js server is running!"</strong> displayed in the browser.</p>
</blockquote>
<p>To <strong>stop the server</strong>, go back to your terminal and press <code>Ctrl + C</code>. The terminal prompt will return, meaning the server has stopped.</p>
<blockquote>
<p>⚠️While the server is running, if you try to type commands in that same terminal window, they won't work. Either open a <strong>new terminal window</strong>, or stop the server first with <code>Ctrl + C</code>.</p>
</blockquote>
<h2><strong>What You've Accomplished</strong></h2>
<p>Look how far you've come! Here's everything you learned in this guide:</p>
<p>📦<strong>Installed Node.js:</strong> Downloaded and set up Node.js LTS on your machine.</p>
<p>🔍<strong>Verified Installation:</strong> Used <code>node --version</code> to confirm everything works.</p>
<p>🎮<strong>Explored the REPL:</strong> Ran JavaScript interactively without writing any files.</p>
<p>📄<strong>Created a JS File:</strong> Wrote your first <code>app.js</code> script with <code>console.log</code>.</p>
<p>▶️<strong>Ran a Script:</strong> Executed your code using the <code>node app.js</code> command.</p>
<p>🌐<strong>Built a Web Server:</strong> Created a real HTTP server that responds in the browser!</p>
<blockquote>
<p><strong>What's next?</strong> From here you can explore reading and writing files with the <code>fs</code> module, accepting user input, understanding npm packages, and eventually building full REST APIs — all without any frameworks to start!</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Creating Routes & Handling Requests with Express.js]]></title><description><![CDATA[If you’ve ever tried building a web server using only built-in Node.js modules, you know it can get complicated quickly. Enter Express.js, the most popular web framework for Node.js. It’s designed to ]]></description><link>https://anilkambarweb.hashnode.dev/creating-routes-handling-requests-with-express-js</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/creating-routes-handling-requests-with-express-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Express Routing]]></category><category><![CDATA[Express JS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend developments]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Fri, 01 May 2026 13:28:16 GMT</pubDate><content:encoded><![CDATA[<p>If you’ve ever tried building a web server using only built-in Node.js modules, you know it can get complicated quickly. Enter <strong>Express.js</strong>, the most popular web framework for Node.js. It’s designed to make building web applications and APIs much faster and easier.</p>
<h2><strong>What is Express.js?</strong></h2>
<p>Imagine you want to open a restaurant. You could build every piece of kitchen equipment from scratch — the oven, the refrigerator, the dishwasher. Or, you could buy reliable appliances that already exist and focus on cooking great food.</p>
<p><strong>Express.js</strong> is like those appliances — for web servers. It is a <em>framework</em> (a toolbox of ready-made code) that sits on top of Node.js and makes it dramatically easier to handle web requests, define URL routes, and send responses back to users.</p>
<blockquote>
<p><strong>📌 Definition</strong></p>
<p>Express.js is a <strong>minimal and flexible web framework</strong> for Node.js. It provides tools for creating web servers, defining URL routes, and sending responses back to clients (like browsers or mobile apps).</p>
</blockquote>
<p>Express.js was created in 2010 and is still the most widely used framework for Node.js today because it’s minimal, flexible, and supported by a large community. When someone visits a website or uses an app, their browser sends an HTTP request to a server, and Express makes it easy for the server to understand that request and send back the correct response—whether it’s an HTML page, data, or a simple status message.</p>
<h2><strong>Why Express simplifies Node.js development</strong></h2>
<p>Node.js can build web servers on its own — but the code gets verbose and repetitive fast. Express wraps all that boilerplate so you write less and do more.</p>
<p>Let's compare the same task — creating a simple web server that says "Hello!" — using raw Node.js versus Express. This will show you exactly what Express saves you from writing.</p>
<p><strong>Without Express (Raw Node)</strong></p>
<pre><code class="language-javascript">const http = require('http');

const server = http.createServer(
  (req, res) =&gt; {
    if (req.url === '/'
     &amp;&amp; req.method === 'GET') {
      res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.end('Hello!');
    } else {
      res.writeHead(404);
      res.end('Not Found');
    }
  }
);

server.listen(3000);
</code></pre>
<p><strong>With Express</strong></p>
<pre><code class="language-javascript">const express = require('express');
const app = express();


app.get('/', (req, res) =&gt; {
  res.send('Hello!');
});




app.listen(3000);
</code></pre>
<p>Both do the same thing. But Express is <strong>shorter, cleaner, and easier to read</strong>. And as your app grows with dozens of routes, the difference becomes even more dramatic. Express also handles 404 errors, JSON parsing, and much more — automatically.</p>
<blockquote>
<p><strong>💡 Key Benefits</strong></p>
<p>Express gives you clean route definitions, built-in response helpers like <code>res.json()</code>, automatic error handling, and a huge ecosystem of plugins called "middleware."</p>
</blockquote>
<h2><strong>Creating your first Express server</strong></h2>
<p>Let's build a working Express server from scratch. You'll need Node.js installed on your computer. If you haven't already, download it from <a href="http://nodejs.org"><strong>nodejs.org</strong></a>.</p>
<ol>
<li><strong>Create a new project folder</strong><br />Open your terminal and run these commands to create a project and install Express.</li>
</ol>
<pre><code class="language-javascript">// Create a new folder for your project
mkdir my-express-app
cd my-express-app

// Set up the project (creates a package.json file)
npm init -y

// Install Express
npm install express
</code></pre>
<ol>
<li><strong>Create your server file</strong><br />Create a file called <code>server.js</code> and add the following code.</li>
</ol>
<pre><code class="language-javascript">// Step 1: Import Express
const express = require('express');

// Step 2: Create an Express "app" (your server)
const app = express();

// Step 3: Define a route (more on this soon!)
app.get('/', (req, res) =&gt; {
  res.send('Hello from Express!');
});

// Step 4: Start listening on port 3000
app.listen(3000, () =&gt; {
  console.log('Server is running on http://localhost:3000');
});
</code></pre>
<ol>
<li><strong>Run your server</strong><br />In the terminal, run <code>node server.js</code> then open your browser and go to <a href="http://localhost:3000"><code>http://localhost:3000</code></a>. You should see "Hello from Express! ".</li>
</ol>
<blockquote>
<p><strong>📖 Understanding the code</strong></p>
<p><code>require('express')</code> loads the library. <code>express()</code> creates your app. <code>app.listen(3000)</code> tells your server to watch for requests on port 3000 — like saying "stand at door number 3000 and wait for visitors."</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/2fdc3053-f1fc-436e-a22a-e17c784d8b46.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Handling GET requests</strong></h2>
<p>A <strong>GET request</strong> is what happens when you type a URL into your browser. You're asking the server: "Give me this page or this data." It's the most common type of request.</p>
<p>In Express, you define a GET route using <code>app.get()</code>. It takes two things: the URL path (like <code>/about</code>) and a <strong>handler function</strong> that decides what to send back.</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// Homepage — responds with a simple welcome message
app.get('/', (req, res) =&gt; {
  res.send('Welcome to the homepage!');
});

// /about — responds with a different message
app.get('/about', (req, res) =&gt; {
  res.send('This is the about page.');
});

// /users — responds with a list of users (as JSON)
app.get('/users', (req, res) =&gt; {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ];
  res.json(users); // Send back JSON data
});

app.listen(3000)
</code></pre>
<h3><strong>Route parameters — making URLs dynamic</strong></h3>
<p>What if you want a route that works for <em>any</em> user ID — like <code>/users/1</code> or <code>/users/42</code>? Use a colon (<code>:</code>) to mark a dynamic segment:</p>
<pre><code class="language-javascript">app.get('/users/:id', (req, res) =&gt; {
  // req.params.id holds whatever was in the URL
  const userId = req.params.id;
  res.send(`You requested user with ID: ${userId}`);
});

// Visiting /users/5 → "You requested user with ID: 5"
// Visiting /users/99 → "You requested user with ID: 99"
</code></pre>
<p><strong>Understanding</strong> <code>req</code> <strong>and</strong> <code>res</code></p>
<p>Every route handler receives two special objects. Think of them as the two sides of a conversation:</p>
<table>
<thead>
<tr>
<th><strong>Object</strong></th>
<th><strong>Full name</strong></th>
<th><strong>What it contains</strong></th>
<th><strong>Example use</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>req</code></td>
<td>request</td>
<td>What the client sent to you</td>
<td><a href="http://req.params.id"><code>req.params.id</code></a>, <a href="http://req.query.name"><code>req.query.name</code></a></td>
</tr>
<tr>
<td><code>res</code></td>
<td>response</td>
<td>What you send back to the client</td>
<td><code>res.send()</code>, <code>res.json()</code></td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/d91e5c0d-5397-4ebc-afff-04e9442ed695.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Handling POST requests</strong></h2>
<p>A <strong>POST request</strong> is used to <em>send data to the server</em> — like submitting a form, creating a new account, or adding an item to a database. Unlike GET requests, POST requests carry a <strong>body</strong> of data.</p>
<p>Before your routes can read the body of a POST request, you need to add one line of setup — a <strong>middleware</strong> that tells Express to parse incoming JSON data automatically:</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// ✅ This middleware lets us read JSON data sent in the request body
app.use(express.json());

// A POST route to create a new user
app.post('/users', (req, res) =&gt; {
  const { name, email } = req.body; // read the data sent by the client

  // In a real app you'd save to a database here
  console.log(`New user: \({name}, \){email}`);

  res.status(201).json({
    message: 'User created!',
    user: { name, email }
  });
});

app.listen(3000);
</code></pre>
<blockquote>
<p><strong>📦 What is middleware?</strong></p>
<p>Middleware is code that runs <em>between</em> receiving a request and sending a response. <code>express.json()</code> is built-in middleware that reads the raw request body and automatically converts it into a JavaScript object available at <code>req.body</code>.</p>
</blockquote>
<h3><strong>Testing your POST route</strong></h3>
<p>You can't test a POST route by just typing in a browser (that only sends GET requests). Use a tool like <strong>Postman</strong> or <strong>Requestly</strong>to send a POST request with a JSON body like this:</p>
<pre><code class="language-javascript">{
  "name": "Alice",
  "email": "alice@example.com"
}

// Expected response:
{
  "message": "User created!",
  "user": {
    "name": "Alice",
    "email": "alice@example.com"
  }
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/7a7e3b7c-91ec-4d2f-b185-19744136aede.png" alt="" style="display:block;margin:0 auto" />

<h2></h2>
<p><strong>Sending responses</strong></p>
<p>Once Express matches a route, you need to send something back. The <code>res</code> object has several methods depending on what kind of response you want to send.</p>
<table>
<thead>
<tr>
<th><strong>Method</strong></th>
<th><strong>What it sends</strong></th>
<th><strong>Common use case</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>res.send()</code></td>
<td>Text or HTML string</td>
<td>Simple messages, HTML pages</td>
</tr>
<tr>
<td><code>res.json()</code></td>
<td>JSON data</td>
<td>APIs returning objects or arrays</td>
</tr>
<tr>
<td><code>res.status()</code></td>
<td>Sets the HTTP status code</td>
<td>Always chain before <code>.send()</code> or <code>.json()</code></td>
</tr>
<tr>
<td><code>res.sendFile()</code></td>
<td>A file from the server</td>
<td>Serving HTML files, images, PDFs</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">// 1. Send plain text
app.get('/hello', (req, res) =&gt; {
  res.send('Hello, World!');
});

// 2. Send JSON data (perfect for APIs)
app.get('/api/user', (req, res) =&gt; {
  res.json({
    name: 'Alice',
    age: 28,
    role: 'developer'
  });
});

// 3. Set a status code + send a message
app.get('/secret', (req, res) =&gt; {
  res.status(403).json({ error: 'Access denied' });
});

// 4. Catch-all 404 handler (always put this LAST)
app.use((req, res) =&gt; {
  res.status(404).send('Page not found!');
});
</code></pre>
<blockquote>
<p><strong>✅ Best practice</strong></p>
<p>Always chain <code>res.status()</code> before <code>.send()</code> or <code>.json()</code> when you need to set a specific status code. The default status is <strong>200</strong> (success), but use <strong>201</strong> for created resources, <strong>400</strong> for bad requests, <strong>404</strong> for not found, and <strong>500</strong> for server errors.</p>
</blockquote>
<h3><strong>Putting it all together</strong></h3>
<pre><code class="language-javascript">const express = require('express');
const app = express();
app.use(express.json()); // enable JSON parsing

// In-memory "database" (just a JS array for this demo)
let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

// GET all users
app.get('/users', (req, res) =&gt; {
  res.json(users);
});

// GET one user by ID
app.get('/users/:id', (req, res) =&gt; {
  const id = Number(req.params.id)
  const user = users.find(u =&gt; u.id === id);
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

// POST create a new user
app.post('/users', (req, res) =&gt; {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// 404 catch-all (must be LAST)
app.use((req, res) =&gt; {
  res.status(404).send('Route not found');
});

app.listen(3000, () =&gt;
  console.log('🚀 Server running at http://localhost:3000')
);
</code></pre>
<h2><strong>Express Routing Structure at a Glance</strong></h2>
<p>Here's how a real Express app's routes might be laid out. Each URL pattern + HTTP method combination maps to exactly one handler function.</p>
<p><strong>Express App — Route Map</strong></p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Route</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>GET</td>
<td><code>/</code></td>
<td>Return the homepage or welcome message</td>
</tr>
<tr>
<td>GET</td>
<td><code>/users</code></td>
<td>Return a list of all users</td>
</tr>
<tr>
<td>GET</td>
<td><code>/users/:id</code></td>
<td>Return a single user by their ID</td>
</tr>
<tr>
<td>POST</td>
<td><code>/users</code></td>
<td>Create a new user from request body</td>
</tr>
<tr>
<td>PUT</td>
<td><code>/users/:id</code></td>
<td>Update an existing user by ID</td>
</tr>
<tr>
<td>DELETE</td>
<td><code>/users/:id</code></td>
<td>Delete a user by ID</td>
</tr>
</tbody></table>
<h2><strong>Cheat sheet</strong></h2>
<p>Here's a summary of everything covered in this guide:</p>
<table>
<thead>
<tr>
<th><strong>What you want to do</strong></th>
<th><strong>The Express way</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Create a server</td>
<td><code>const app = express()</code></td>
</tr>
<tr>
<td>Handle a GET request</td>
<td><code>app.get('/path', handler)</code></td>
</tr>
<tr>
<td>Handle a POST request</td>
<td><a href="http://app.post"><code>app.post</code></a><code>('/path', handler)</code></td>
</tr>
<tr>
<td>Read URL parameters</td>
<td><a href="http://req.params.id"><code>req.params.id</code></a></td>
</tr>
<tr>
<td>Read POST body data</td>
<td><code>req.body</code> (after <code>app.use(express.json())</code>)</td>
</tr>
<tr>
<td>Send a text response</td>
<td><code>res.send('text')</code></td>
</tr>
<tr>
<td>Send a JSON response</td>
<td><code>res.json({ key: 'value' })</code></td>
</tr>
<tr>
<td>Set a status code</td>
<td><code>res.status(201).json(...)</code></td>
</tr>
<tr>
<td>Start the server</td>
<td><code>app.listen(3000)</code></td>
</tr>
</tbody></table>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[URL Parameters vs Query Strings in Express.js]]></title><description><![CDATA[When you're building your first web app with Express.js, you’ll notice that URLs do more than just point to a page—they carry data. But how that data is packed into the URL matters.
In the world of Ex]]></description><link>https://anilkambarweb.hashnode.dev/url-parameters-vs-query-strings-in-express-js</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/url-parameters-vs-query-strings-in-express-js</guid><category><![CDATA[Query Parameters]]></category><category><![CDATA[query string]]></category><category><![CDATA[Express]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Fri, 01 May 2026 12:14:50 GMT</pubDate><content:encoded><![CDATA[<p>When you're building your first web app with Express.js, you’ll notice that URLs do more than just point to a page—they carry data. But how that data is packed into the URL matters.</p>
<p>In the world of Express, we primarily deal with two types: <strong>URL Parameters</strong> and <strong>Query Strings</strong>. Let’s break them down so you know exactly which one to use and when.</p>
<h2><strong>Anatomy of a URL</strong></h2>
<p>Before diving into params and queries, let's look at what a URL is actually made of. Every URL you type into a browser tells the server <em>where</em> to go and <em>what</em> to bring back.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/a4fed3e9-79ea-4bde-be55-40529b14d83c.png" alt="" style="display:block;margin:0 auto" />

<p>Think of it this way: the <strong>URL parameter</strong> is like the house number on a street — it points to a specific thing. The <strong>query string</strong> is like instructions you give once you're there — "show me only the red ones, sorted by price".</p>
<h2><strong>URL Parameters</strong></h2>
<p>A <strong>URL parameter</strong> (also called a "route parameter" or "path parameter") is a named segment in the URL path. It acts as a unique <em>identifier</em> for a specific resource.  </p>
<p><strong>Real-world analogy</strong></p>
<p>Imagine a library. Every book has a unique ID number. When you want <em>book number 101</em>, you go directly to shelf 101. The number in the path tells you <strong>exactly which thing</strong> you want.</p>
<pre><code class="language-javascript">// Route definition in Express
app.get('/users/:userId', (req, res) =&gt; {
  // :userId is a URL parameter
});

// Example URLs that match this route:
// /users/42       → userId = "42"
// /users/alice    → userId = "alice"
// /users/99       → userId = "99"
</code></pre>
<p>Notice the colon (<code>:</code>) in front of <code>userId</code> — that's how Express knows it's a parameter placeholder, not a fixed path.</p>
<blockquote>
<p><strong>Key idea</strong></p>
<p>URL parameters are part of the <strong>path itself</strong>. If the parameter is missing, the URL doesn't match the route at all. They are required and identify a resource uniquely.</p>
</blockquote>
<h3><strong>More examples</strong></h3>
<pre><code class="language-javascript">// Product page
app.get('/products/:productId', ...);
// → /products/shoes-nike-air

// Blog post
app.get('/posts/:slug', ...);
// → /posts/my-first-blog-post

// Multiple parameters in one route
app.get('/users/:userId/orders/:orderId', ...);
// → /users/5/orders/102
</code></pre>
<h2><strong>Query Strings</strong></h2>
<p>A <strong>query string</strong> comes <em>after</em> the <code>?</code> in a URL. It holds key-value pairs separated by <code>&amp;</code>. Instead of identifying a resource, query strings <em>filter, sort, or modify</em> what comes back.  </p>
<p><strong>Real-world analogy</strong></p>
<p>You're at a restaurant. You order "pasta" (the resource). But then you add: "make it vegetarian, medium spice, no garlic". Those extra instructions are the query string — they <strong>shape the result</strong> without changing what resource you're asking for.</p>
<pre><code class="language-javascript">// URL: /products?category=shoes&amp;sort=price&amp;limit=20

app.get('/products', (req, res) =&gt; {
  // Query strings are optional — route still matches without them
  // /products        → works fine (no filters)
  // /products?sort=price → also works
});
</code></pre>
<blockquote>
<p><strong>Key idea</strong></p>
<p>Query strings are always <strong>optional</strong>. The route works with or without them. They're great for search filters, sorting, pagination, and any time the user can narrow down results.</p>
</blockquote>
<h2><strong>Key Differences</strong></h2>
<p>Here's a side-by-side comparison to make the distinction crystal clear:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/67beb2f7-f558-4079-8bde-6d2f28fefa45.png" alt="" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th><strong>Feature</strong></th>
<th><strong>URL Parameter</strong></th>
<th><strong>Query String</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Position in URL</td>
<td>Inside the path (<code>/path/:id</code>)</td>
<td>After <code>?</code> at the end</td>
</tr>
<tr>
<td>Required?</td>
<td>Yes — route won't match</td>
<td>No — always optional</td>
</tr>
<tr>
<td>Use case</td>
<td>Identify one thing</td>
<td>Filter or sort things</td>
</tr>
<tr>
<td>Express access</td>
<td><a href="http://req.params.name"><code>req.params.name</code></a></td>
<td><a href="http://req.query.name"><code>req.query.name</code></a></td>
</tr>
<tr>
<td>Multiple values</td>
<td>Use separate route segments</td>
<td>Use <code>&amp;</code> to join pairs</td>
</tr>
</tbody></table>
<h2><strong>Accessing Them in Express</strong></h2>
<h3><strong>Reading URL Parameters —</strong> <code>req.params</code></h3>
<p>Express stores URL parameters in the <code>req.params</code> object. The key is whatever you named after the colon in your route definition.</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// Route definition: :userId is a named parameter
app.get('/users/:userId', (req, res) =&gt; {
  const id = req.params.userId;
  res.send(`Fetching profile for user: ${id}`);
});

// GET /users/42  →  "Fetching profile for user: 42"
// GET /users/alice  →  "Fetching profile for user: alice"
</code></pre>
<h3><strong>Reading Query Strings —</strong> <code>req.query</code></h3>
<p>Express automatically parses the query string and stores everything in <code>req.query</code>. You don't need to do anything special in the route definition.</p>
<pre><code class="language-javascript">app.get('/products', (req, res) =&gt; {
  const category = req.query.category;
  const sort     = req.query.sort;
  const limit    = req.query.limit;

  res.json({ category, sort, limit });
});

// GET /products?category=shoes&amp;sort=price&amp;limit=20
// → { category: "shoes", sort: "price", limit: "20" }

// GET /products  (no query)
// → { category: undefined, sort: undefined, limit: undefined }
</code></pre>
<blockquote>
<p><strong>Pro tip</strong></p>
<p>Always check if a query value exists before using it — it will be <code>undefined</code> if the user didn't include it. Use a default value: <code>const sort = req.query.sort || 'asc';</code></p>
</blockquote>
<h3><strong>Using Both Together</strong></h3>
<p>The real power comes from combining them. Use a URL parameter to identify <em>which</em> resource, and query strings to control <em>how</em> it's returned.</p>
<pre><code class="language-javascript">// URL: /users/42/posts?status=published&amp;page=2

app.get('/users/:userId/posts', (req, res) =&gt; {
  const userId = req.params.userId;   // "42"
  const status = req.query.status;    // "published"
  const page   = req.query.page;      // "2"

  // Translation: "Give me user 42's posts,
  // but only the published ones, page 2"
  res.json({ userId, status, page });
});
</code></pre>
<h2><strong>When to Use Which</strong></h2>
<p>A simple question helps every time: <em>"Am I identifying a specific thing, or am I filtering/sorting a list of things?"</em></p>
<table>
<thead>
<tr>
<th><strong>Scenario</strong></th>
<th><strong>Use</strong></th>
<th><strong>Example URL</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Get a specific user by ID</td>
<td><strong>URL Param</strong></td>
<td><code>/users/42</code></td>
</tr>
<tr>
<td>Search users by name</td>
<td><strong>Query String</strong></td>
<td><code>/users?name=alice</code></td>
</tr>
<tr>
<td>Get a specific blog post</td>
<td><strong>URL Param</strong></td>
<td><code>/posts/my-first-post</code></td>
</tr>
<tr>
<td>List posts, sorted by date</td>
<td><strong>Query String</strong></td>
<td><code>/posts?sort=newest</code></td>
</tr>
<tr>
<td>Delete a specific order</td>
<td><strong>URL Param</strong></td>
<td><code>/orders/99</code></td>
</tr>
<tr>
<td>Filter orders by status</td>
<td><strong>Query String</strong></td>
<td><code>/orders?status=pending</code></td>
</tr>
<tr>
<td>Paginate a results list</td>
<td><strong>Query String</strong></td>
<td><code>/products?page=3&amp;limit=10</code></td>
</tr>
</tbody></table>
<blockquote>
<p><strong>The mental model</strong></p>
<p><strong>URL parameters</strong> are nouns — they name the thing. <strong>Query strings</strong> are adjectives — they describe how you want it. <em>"Give me the user (noun) who is currently online (adjective)."</em></p>
</blockquote>
<h4><strong>Quick Reference Cheatsheet</strong></h4>
<table>
<thead>
<tr>
<th>Syntax / Code</th>
<th>What It Does</th>
<th>Example URL</th>
<th>Explanation</th>
</tr>
</thead>
<tbody><tr>
<td><code>req.params.id</code></td>
<td>Read a URL parameter named <code>id</code></td>
<td><code>/users/123</code></td>
<td>Gets <code>123</code> from the URL</td>
</tr>
<tr>
<td><code>req.query.sort</code></td>
<td>Read a query string key named <code>sort</code></td>
<td><code>/users?sort=asc</code></td>
<td>Gets <code>asc</code> from query</td>
</tr>
<tr>
<td><code>/route/:param</code></td>
<td>Define a URL parameter in a route</td>
<td><code>/users/:id</code></td>
<td><code>id</code> becomes dynamic</td>
</tr>
<tr>
<td><code>/route?key=val</code></td>
<td>Send query parameters (no route change needed)</td>
<td><code>/users?age=25</code></td>
<td>Filters data</td>
</tr>
<tr>
<td><code>key=a&amp;key2=b</code></td>
<td>Multiple query parameters using <code>&amp;</code></td>
<td><code>/users?age=25&amp;city=Pune</code></td>
<td>Multiple filters</td>
</tr>
</tbody></table>
<h3>You've got it! Here's the one-liner:</h3>
<ul>
<li><p>Use <strong>URL parameters</strong> when you need to <strong>identify a specific resource</strong> — like a user ID or post slug.</p>
</li>
<li><p>Use <strong>query strings</strong> when you want to <strong>filter, sort, or paginate</strong> a list of resources.</p>
</li>
<li><p>Both are available in Express via <strong>req.params</strong> and <strong>req.query</strong> respectively.</p>
</li>
</ul>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[What is Node.js? JavaScript on the Server Side]]></title><description><![CDATA[For a long time, JavaScript was like a high-end chef who only worked in one specific kitchen: the web browser. If you wanted to make a website interactive—like adding a pop-up menu or a smooth image g]]></description><link>https://anilkambarweb.hashnode.dev/what-is-node-js-javascript-on-the-server-side</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/what-is-node-js-javascript-on-the-server-side</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[backend developments]]></category><category><![CDATA[Node JS Development Services]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Thu, 30 Apr 2026 21:57:00 GMT</pubDate><content:encoded><![CDATA[<p>For a long time, JavaScript was like a high-end chef who only worked in one specific kitchen: <strong>the web browser</strong>. If you wanted to make a website interactive—like adding a pop-up menu or a smooth image gallery—JavaScript was your go-to tool. But it couldn't leave the building.</p>
<p>Then came <strong>Node.js</strong>, and suddenly, that chef could cook anywhere.</p>
<h2><strong>What Is Node.js?</strong></h2>
<p>You may have heard of JavaScript — the programming language that makes web pages interactive. It runs inside your browser: when a button changes color when you hover over it, or a form validates before you submit, that's JavaScript doing its job.</p>
<p>For a long time, JavaScript could <em>only</em> do that. It lived inside the browser and nowhere else. If you wanted to build a server — the computer-side part of an app that stores your data, handles logins, or talks to databases — you had to use a different language entirely, like PHP, Python, Ruby, or Java.</p>
<p>Then in 2009, a developer named <strong>Ryan Dahl</strong> had a simple but powerful idea: <em>what if JavaScript could run outside the browser, too?</em> The result was <strong>Node.js</strong>.</p>
<blockquote>
<p><strong>Simple Definition</strong></p>
<p><strong>Node.js is a runtime environment</strong> — a program that lets you run JavaScript code on a server (or your own computer), completely outside of any web browser.</p>
</blockquote>
<p>Think of it this way. JavaScript is the language — like English. A browser is one place you can speak English. Node.js is another place you can speak that same language, just in a different context: a server room instead of a webpage.</p>
<h2><strong>Why Was JavaScript Browser-Only at First?</strong></h2>
<p>JavaScript was created in 1995, specifically to make HTML pages more interactive in the Netscape browser. It was never designed to talk to filesystems, databases, or networks on its own. Its entire world was the browser's sandbox — a carefully limited environment designed to keep websites from doing dangerous things on your computer.</p>
<p>Servers needed to do very different things: read and write files, query databases, handle user authentication, send emails, and more. Those tasks required full access to the operating system — something browsers deliberately blocked.</p>
<p>So for over a decade, web developers had to be bilingual. JavaScript for the front end (what the user sees), and a completely separate language for the back end (the server logic).</p>
<p><strong>Before Node.js:</strong></p>
<h4><strong>🎭 Front-end developer</strong></h4>
<p>Writes JavaScript. Handles buttons, animations, and what the user sees.</p>
<h4><strong>🗄️ Back-end developer</strong></h4>
<p>Writes PHP, Java, or Python. Handles databases, logins, and the server.  </p>
<p>They were two separate teams, writing two separate codebases, in two separate languages. It worked — but it was slow, expensive, and created a lot of friction when features needed to change on both sides.</p>
<h2><strong>How Node.js Lets JavaScript Run on Servers</strong></h2>
<p>To understand how Node.js pulled this off, you need to know about one crucial piece of technology: the <strong>V8 engine</strong>.</p>
<h3><strong>The V8 Engine (In Plain English)</strong></h3>
<p>Inside Google Chrome, there's a component called V8. Its only job is to take JavaScript code — which is human-readable text — and translate it into machine code that the computer's processor can actually execute. V8 does this blazing fast, which is why Chrome is so quick at running JavaScript.</p>
<p>Ryan Dahl took V8, which was open-source, and <em>ripped it out of the browser</em>. He then wrapped it with additional code that gave JavaScript new powers it never had in the browser:</p>
<blockquote>
<p><strong>What Node.js adds on top of V8</strong></p>
<p>The ability to read and write files on disk, make network requests, talk to databases, listen on a port (like a web server does), and access the operating system — things that are deliberately blocked inside browsers.</p>
</blockquote>
<p>The result: you write JavaScript, Node.js feeds it to V8 for execution, and you have a fully capable server application. Same language, entirely new context.  </p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/33a8d806-142f-486f-90d6-3f69235e80bb.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>The Event-Driven Idea: Why Node.js Is Fast</strong></h2>
<p>Now here's where Node.js gets clever. Traditional servers — think PHP or Java — handle requests in a very straightforward but sometimes slow way. When a user asks for data from a database, the server <em>waits</em> for the database to reply before it does anything else. Meanwhile, all other incoming users have to wait in line.</p>
<p>This is called <strong>blocking</strong> — the server is blocked, doing nothing, until that one task finishes.</p>
<blockquote>
<p><strong>Analogy: The Waiter</strong></p>
<p>A traditional server is like a waiter who takes your order, walks to the kitchen, stands there watching the chef cook, brings your food, and <em>only then</em> goes to take another table's order. Imagine how slow a restaurant would be!</p>
</blockquote>
<p>Node.js does something different. Instead of waiting, it says: <em>"Go start cooking, and call me when it's done. In the meantime, I'll take more orders."</em></p>
<p>This is the <strong>event-driven, non-blocking model</strong>. Node.js registers a callback — essentially a note saying "when this task finishes, run this code" — then moves on immediately to handle the next request. When the database replies (the "event"), Node.js picks up that callback and processes the result.</p>
<p>The result is a server that can handle thousands of simultaneous connections very efficiently, even on modest hardware.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/25c0dee5-6ae5-420f-ba2d-77b3fad89fc8.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Node.js vs Traditional Backends</strong>  </p>
<p>You'll often hear Node.js compared to PHP (which powers WordPress), Java (used in large enterprise apps), or Python. Here's a straightforward comparison for beginners.</p>
<table>
<thead>
<tr>
<th><strong>Feature</strong></th>
<th><strong>PHP / Java / Python</strong></th>
<th><strong>Node.js</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Language</strong></td>
<td>PHP, Java, Python (separate from front end)</td>
<td>JavaScript (same as front end)</td>
</tr>
<tr>
<td><strong>Request handling</strong></td>
<td>Typically blocking (waits for one task)</td>
<td><strong>Non-blocking</strong> (handles many at once)</td>
</tr>
<tr>
<td><strong>Best for</strong></td>
<td>CPU-heavy tasks, traditional web apps</td>
<td>Real-time apps, APIs, streaming data</td>
</tr>
<tr>
<td><strong>Learning curve</strong></td>
<td>Need to learn a second language if you know JS</td>
<td><strong>Use JS everywhere</strong></td>
</tr>
<tr>
<td><strong>Package ecosystem</strong></td>
<td>Mature, language-specific tools</td>
<td>npm — largest package registry in the world</td>
</tr>
<tr>
<td><strong>Speed</strong></td>
<td>Good — mature, well-optimised</td>
<td><strong>Very fast</strong> for I/O-heavy workloads</td>
</tr>
<tr>
<td><strong>When to reconsider</strong></td>
<td>—</td>
<td><strong>CPU-intensive tasks</strong> (e.g. video encoding) are not its strength</td>
</tr>
</tbody></table>
<p>Node.js isn't always the right choice — no tool is. But for building fast APIs, real-time features, and full-stack JavaScript apps, it's extremely well-suited.</p>
<h2><strong>Real-World Uses of Node.js</strong></h2>
<p><strong>Chat applications:</strong> Real-time messaging (like Slack) needs to push messages instantly. Node.js handles thousands of open connections at once.</p>
<p><strong>REST APIs:</strong> The "middleman" that your mobile or web app talks to when fetching data. Node.js with Express is a very popular stack.</p>
<p><strong>Online games:</strong> Multiplayer games need fast, low-latency communication. Node.js's non-blocking design makes it ideal.</p>
<p><strong>Streaming data:</strong> Netflix uses Node.js for parts of its infrastructure — handling millions of simultaneous streams efficiently.</p>
<p><strong>E-commerce backends:</strong> High-traffic shopping sites use Node.js to handle bursts of requests during sales without crashing.</p>
<p><strong>Developer tools:</strong> Build tools like Webpack, Vite, and ESLint all run on Node.js. Even VS Code's language server uses it.</p>
<h2><strong>The Big Picture</strong></h2>
<p>Here's everything we covered, distilled to its essence:</p>
<h3><strong>Key Takeaways</strong></h3>
<p><strong>JavaScript</strong> was created for browsers — interactive web pages.</p>
<p><strong>Node.js</strong> took JavaScript's engine (V8) out of the browser and put it on servers, giving JS the ability to read files, query databases, and run as a web server.</p>
<p><strong>Its event-driven model</strong> means it never sits around waiting — it handles many requests at once by registering callbacks and moving on.</p>
<p><strong>The big win:</strong> developers can now use one language — JavaScript — for the entire stack: the UI in the browser and the server behind it.</p>
<p>If you want to go further, the next steps are learning <strong>npm</strong> (Node's package manager), then a framework like <strong>Express</strong> to build your first web server. You're already speaking the language — Node.js just gave it a new place to live.</p>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[What is Middleware in Express and How It Works]]></title><description><![CDATA[If you’re just starting your journey with Node.js and Express, you’ll quickly run into the term Middleware. While it sounds highly technical, the concept is actually very intuitive.
Think of an Expres]]></description><link>https://anilkambarweb.hashnode.dev/what-is-middleware-in-express-and-how-it-works</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/what-is-middleware-in-express-and-how-it-works</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[Express]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Thu, 30 Apr 2026 17:32:46 GMT</pubDate><content:encoded><![CDATA[<p>If you’re just starting your journey with Node.js and Express, you’ll quickly run into the term <strong>Middleware</strong>. While it sounds highly technical, the concept is actually very intuitive.</p>
<p>Think of an Express application as a <strong>pipeline</strong>. On one end, a user sends a <strong>Request</strong> (like clicking a link or submitting a form), and on the other end, the server sends back a <strong>Response</strong> (like showing a webpage or a "Success" message). Middleware is literally everything that happens "in the middle" of that journey.</p>
<p>You can visualize middleware as a series of <strong>checkpoints</strong> your request must pass through before reaching its final destination. At each stop, the middleware can inspect the request, modify it, or even stop it entirely if something is wrong (like a missing password). By breaking your server's logic into these smaller checkpoints, you keep your code organized and easy to manage.</p>
<h2>What is Middleware?</h2>
<p>Imagine you're going through airport security. Before you reach your flight gate (the final destination), you pass through a series of checkpoints — ticket check, baggage scan, identity verification. Each checkpoint can either <strong>let you through</strong>, <strong>stop you</strong>, or <strong>modify something</strong> (like removing your shoes).</p>
<p>In Express, <strong>middleware</strong> works exactly like this. It's a function that sits between the incoming request and the final route handler. It can inspect the request, modify it, run some logic, and then decide whether to pass it forward or stop it entirely.</p>
<blockquote>
<p><strong>Simple definition:</strong> Middleware is a function that has access to the request object (<code>req</code>), the response object (<code>res</code>), and a special <code>next</code> function that passes control to the next middleware in line.</p>
</blockquote>
<p>Every middleware function looks like this:</p>
<pre><code class="language-javascript">function myMiddleware(req, res, next) {
  // Do something with the request or response
  console.log('A request just came in!');

  // Call next() to pass control to the next middleware
  next();
}
</code></pre>
<h2>Where Middleware Sits in the Request</h2>
<p>Lifecycle</p>
<p>Every time a user visits your app or an API is called, a <strong>request</strong> travels through a pipeline. Middleware functions are the stops along that pipeline before the final route handler sends back a response.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/2c32dca5-6fe4-4014-8c49-c9ea785d28d5.png" alt="" style="display:block;margin:0 auto" />

<p>The request travels left to right through each middleware. Each stop has the power to modify things, log something, check credentials, and then call <code>next()</code> to continue the journey — or stop entirely by sending a response.</p>
<h2>Types of Middleware in Express</h2>
<p>Express organizes middleware into three main types based on where and how they are used.</p>
<p><strong>Application-level:</strong> Runs for every request that hits your entire app. Registered with <code>app.use()</code>.<br /><strong>Router-level:</strong> Runs only for routes within a specific router. Registered with <code>router.use()</code>.<br /><strong>Built-in:</strong> Comes included with Express. Examples: <code>express.json()</code>, <code>express.static()</code>.</p>
<h3><strong>Application-level Middleware</strong></h3>
<p>This type of middleware is attached to the <strong>entire app</strong> using <code>app.use()</code>. It runs on every single request unless you give it a specific path.</p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// This runs on EVERY request
app.use((req, res, next) =&gt; {
  console.log(`\({req.method} \){req.url}`);
  next(); // Pass to the next middleware
});

// This runs only on /users path
app.use('/users', (req, res, next) =&gt; {
  console.log('A /users request came in');
  next();
});
</code></pre>
<h3><strong>Router-level Middleware</strong></h3>
<p>Works the same as application-level middleware, but it's attached to an <code>express.Router()</code> instance. This is great for <strong>grouping related routes</strong> (like all <code>/admin</code> routes) and applying middleware only to them.</p>
<pre><code class="language-javascript">const express = require('express');
const router = express.Router();

// Only runs for routes in this router
router.use((req, res, next) =&gt; {
  console.log('Admin route accessed');
  next();
});

router.get('/dashboard', (req, res) =&gt; {
  res.send('Admin Dashboard');
});

module.exports = router;
</code></pre>
<h3><strong>Built-in Middleware</strong></h3>
<p>Express ships with a few useful middleware functions out of the box — no extra packages needed.</p>
<pre><code class="language-javascript">// Parse incoming JSON bodies (for POST/PUT requests)
app.use(express.json());

// Parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));

// Serve static files (HTML, CSS, images) from a folder
app.use(express.static('public'));
</code></pre>
<h2>Execution Order of Middleware</h2>
<p>This is one of the most important things to understand about Express: <strong>middleware runs in the order it is defined</strong>. Think of it like a queue — first in, first served.</p>
<blockquote>
<p><strong>Order matters!</strong> If you define a route before a middleware, that middleware will NOT run for that route. Always register middleware before your routes.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/2ca2967d-653a-44d9-87ba-ad4cbb7701a8.png" alt="" style="display:block;margin:0 auto" />

<h2>The Role of <code>next()</code></h2>
<p>The <code>next()</code> function is the <strong>handoff baton</strong> in your middleware chain. When a middleware function calls <code>next()</code>, it tells Express: <em>"I'm done here, pass the request to the next one."</em></p>
<p>If you forget to call <code>next()</code>, the request gets <strong>stuck</strong> — your app will stop responding and the browser will keep waiting forever.</p>
<pre><code class="language-javascript">// ✅ Pass to the next middleware
app.use((req, res, next) =&gt; {
  console.log('Logging...');
  next(); // ← Moves to next
});

// 🚫 Stop here and send a response (blocks chain)
app.use((req, res, next) =&gt; {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
    // next() is NOT called — chain stops here
  }
  next();
});

// ⚠️ Forward an error to error-handling middleware
app.use((req, res, next) =&gt; {
  next(new Error('Something went wrong'));
});
</code></pre>
<blockquote>
<p><strong>Pro tip:</strong> When sending a response inside middleware (like a 401 error), add a <code>return</code> before it. This prevents code from continuing to run <em>and</em> prevents accidentally calling <code>next()</code> after already sending a response</p>
</blockquote>
<h2>Real-World Examples</h2>
<p>Now let's see middleware doing actual useful work. These three patterns show up in almost every Express application.</p>
<h4><strong>1. Logging: Request Logger</strong></h4>
<p>Logs every request with its method, URL, and how long it took. Helps you debug and monitor your app.</p>
<pre><code class="language-javascript">function logger(req, res, next) {
  const start = Date.now();
  console.log(`→ \({req.method} \){req.url}`);

  // Listen for when the response finishes
  res.on('finish', () =&gt; {
    const ms = Date.now() - start;
    console.log(`← \({res.statusCode} (\){ms}ms)`);
  });

  next(); // Always pass through
}

app.use(logger);
</code></pre>
<h4><strong>2. Authentication: Token Checker</strong></h4>
<p>Checks if the request carries a valid token before allowing access to protected routes. If not, it stops the chain and returns a 401.</p>
<pre><code class="language-javascript">function authenticate(req, res, next) {
  const token = req.headers['authorization'];

  if (!token) {
    // Stop here — no token found
    return res.status(401).json({
      error: 'No token provided'
    });
  }

  if (token !== 'my-secret-token') {
    return res.status(403).json({
      error: 'Invalid token'
    });
  }

  // Token is valid — continue!
  next();
}

// Apply only to /dashboard
app.get('/dashboard', authenticate, (req, res) =&gt; {
  res.send('Welcome to the dashboard!');
});
</code></pre>
<h4><strong>3. Validation: Request Body Validator</strong></h4>
<p>Checks that required fields exist in the request body before letting it reach the route handler. Prevents bad data from ever touching your database.</p>
<pre><code class="language-javascript">function validateUser(req, res, next) {
  const { name, email } = req.body;

  if (!name || !email) {
    // Missing fields — stop here
    return res.status(400).json({
      error: 'Name and email are required'
    });
  }

  if (!email.includes('@')) {
    return res.status(400).json({
      error: 'Invalid email format'
    });
  }

  // All good — move on
  next();
}

app.post('/users', validateUser, (req, res) =&gt; {
  // We know req.body is valid here
  res.status(201).json({ message: 'User created!' });
});
</code></pre>
<h2>Quick Reference Summary</h2>
<table>
<thead>
<tr>
<th><strong>Concept</strong></th>
<th><strong>What it means</strong></th>
<th><strong>When to use</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>app.use(fn)</code></td>
<td>Registers middleware for all routes</td>
<td>Logging, parsing, CORS headers</td>
</tr>
<tr>
<td><code>router.use(fn)</code></td>
<td>Middleware for a group of routes</td>
<td>Admin-only or API-only sections</td>
</tr>
<tr>
<td><code>next()</code></td>
<td>Pass control to the next function</td>
<td>When your middleware is done</td>
</tr>
<tr>
<td><code>return res.json()</code></td>
<td>Send a response and stop the chain</td>
<td>Validation fails, auth rejected</td>
</tr>
<tr>
<td><code>express.json()</code></td>
<td>Built-in body parser for JSON</td>
<td>Any POST/PUT route with a JSON body</td>
</tr>
<tr>
<td><code>express.static()</code></td>
<td>Serves static files automatically</td>
<td>Serving HTML, CSS, images</td>
</tr>
</tbody></table>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[Understanding Map & Set in JavaScript]]></title><description><![CDATA[If you’ve been coding in JavaScript for a while, you’re likely very comfortable with Arrays and Objects. They are the bread and butter of data storage. However, as your apps grow, you might find that ]]></description><link>https://anilkambarweb.hashnode.dev/understanding-map-set-in-javascript</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/understanding-map-set-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Web Dev 2026]]></category><category><![CDATA[mapvsset]]></category><category><![CDATA[map and set in javascript]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 26 Apr 2026 18:21:45 GMT</pubDate><content:encoded><![CDATA[<p>If you’ve been coding in JavaScript for a while, you’re likely very comfortable with <strong>Arrays</strong> and <strong>Objects</strong>. They are the bread and butter of data storage. However, as your apps grow, you might find that Objects and Arrays have some annoying quirks.</p>
<p>That’s where <strong>Map</strong> and <strong>Set</strong> come in. Introduced in ES6, these data structures are designed to handle specific tasks more efficiently. Let’s break them down!</p>
<h2><strong>The Problem with Objects &amp; Arrays</strong></h2>
<p>In JavaScript, we've always had two main ways to store data:</p>
<ul>
<li><p><strong>Objects</strong> — to store key-value pairs (like a dictionary)</p>
</li>
<li><p><strong>Arrays</strong> — to store a list of values in order</p>
</li>
</ul>
<p>These are great! But they come with some annoying problems. Let's look at them.</p>
<h3><strong>Problem 1 — Objects only allow string keys</strong></h3>
<p>Imagine you want to use a number or another object as a key. With a plain object, that doesn't work well:</p>
<pre><code class="language-javascript">const scores = {};
scores[1]   = "gold";
scores[2]   = "silver";

console.log(Object.keys(scores));
// → ["1", "2"]   ← Numbers turned into strings! 😟
</code></pre>
<blockquote>
<p><strong>⚠️ Heads up</strong></p>
<p>JavaScript objects secretly convert all keys to strings. If you use a number or an object as a key, it gets "stringified" — which can cause hard-to-find bugs.</p>
</blockquote>
<h3><strong>Problem 2 — Arrays allow duplicate values</strong></h3>
<p>What if you want to store a unique list of items — say, unique usernames who visited a page? An array happily lets duplicates in:</p>
<pre><code class="language-javascript">const visitors = ["alice", "bob", "alice", "charlie", "bob"];

// How many unique visitors? You'd have to manually filter!
const unique = visitors.filter((v, i) =&gt; visitors.indexOf(v) === i);
console.log(unique); // ["alice", "bob", "charlie"]
</code></pre>
<p>That filter trick works — but it's clunky. There's a better way. Enter <strong>Map</strong> and <strong>Set</strong>.</p>
<h2><strong>What is a Map?</strong></h2>
<p>A <strong>Map</strong> is like an upgraded object. It stores <strong>key → value</strong> pairs — just like an object — but it fixes the key problem. In a Map, <em>keys can be anything</em>: numbers, strings, objects, even functions.</p>
<p>Think of a Map like a real-world dictionary or a contacts list on your phone — each contact name (key) points to a phone number (value).</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/e66221d6-eaf0-49fb-a36c-871667a6b06a.png" alt="" style="display:block;margin:0 auto" />

  
<p><strong>How to use a Map</strong></p>
<pre><code class="language-javascript">// 1. Create a Map
const myMap = new Map();

// 2. Add values using .set(key, value)
myMap.set("name", "Alice");
myMap.set(42, "the answer");
myMap.set(true, "yes it works");

// 3. Read values using .get(key)
console.log(myMap.get("name")); // → "Alice"
console.log(myMap.get(42));    // → "the answer"

// 4. Check if a key exists
console.log(myMap.has("name")); // → true

// 5. Count entries
console.log(myMap.size); // → 3

// 6. Delete a key
myMap.delete(42);

// 7. Loop through all entries
myMap.forEach((value, key) =&gt; {
  console.log(key, "→", value);
});
</code></pre>
<blockquote>
<p><strong>✅ Remember</strong></p>
<p>You use <code>.set()</code> to add, <code>.get()</code> to read, and <code>.has()</code> to check. These three methods cover most of what you'll ever need from a Map.</p>
</blockquote>
<h3><strong>What is a Set?</strong></h3>
<p>A <strong>Set</strong> is a collection of <em>unique values</em>. It's like an array, but it <strong>automatically removes duplicates</strong>. No extra code needed!</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/e779a018-a0cd-4d0a-ae70-0c0174a83e30.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>How to use a Set</strong></h3>
<pre><code class="language-javascript">// 1. Create a Set
const fruits = new Set();

// 2. Add values using .add()
fruits.add("apple");
fruits.add("banana");
fruits.add("apple");  // duplicate! Set ignores this
fruits.add("mango");

console.log(fruits.size); // → 3 (not 4!)

// 3. Check if value exists
console.log(fruits.has("banana")); // → true

// 4. Remove a value
fruits.delete("banana");

// 5. Loop through
fruits.forEach(fruit =&gt; console.log(fruit));

// 6. SUPERPOWER: Remove duplicates from an array instantly!
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
console.log(unique); // → [1, 2, 3]
</code></pre>
<blockquote>
<p><strong>💡 Pro Tip</strong></p>
<p>The trick <code>[...new Set(array)]</code> is one of the most popular JavaScript one-liners. It removes all duplicates from an array in a single line. Memorise it!</p>
</blockquote>
<h2><strong>Map vs Object</strong></h2>
<p>Both Map and Object store key-value pairs. So when do you use which? Here's a clear comparison:</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Map</th>
<th>Object</th>
</tr>
</thead>
<tbody><tr>
<td>Key Types</td>
<td>Keys can be any type (number, object, boolean...)</td>
<td>Keys must be strings or symbols only</td>
</tr>
<tr>
<td>Order</td>
<td>Remembers insertion order</td>
<td>Order not always guaranteed</td>
</tr>
<tr>
<td>Size</td>
<td>Has a built-in <code>.size</code> property</td>
<td>No built-in size (need <code>Object.keys().length</code>)</td>
</tr>
<tr>
<td>Iteration</td>
<td>Easier to iterate (loop through)</td>
<td>Less direct iteration compared to Map</td>
</tr>
<tr>
<td>Performance Use Case</td>
<td>Better for frequent add/delete operations</td>
<td>Better for fixed, structured data</td>
</tr>
<tr>
<td>JSON Support</td>
<td>Not directly compatible with JSON</td>
<td>Works with JSON directly</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">// Object — keys become strings
const obj = {};
obj[1] = "one";
console.log(Object.keys(obj)); // → ["1"]  (number became a string!)

// Map — keys keep their original type
const map = new Map();
map.set(1, "one");
console.log([...map.keys()]); // → [1]  (still a number ✅)
</code></pre>
<blockquote>
<p><strong>🧠 Simple Rule</strong></p>
<p>Use an <strong>Object</strong> when you're describing a "thing" (like a user profile). Use a <strong>Map</strong> when you're building a lookup table or dictionary where you need non-string keys or frequent updates.</p>
</blockquote>
<h2><strong>Set vs Array</strong></h2>
<p>Both Set and Array hold a list of values. The big difference? <strong>Sets only store unique values</strong>, and they're faster at checking if something exists.</p>
<pre><code class="language-javascript">// Array — allows duplicates, slow to check membership
const arr = ["red", "blue", "red"];
console.log(arr.includes("red")); // → true (but slow for big lists)
console.log(arr.length);           // → 3 (counts duplicates!)

// Set — unique only, fast membership check
const set = new Set(["red", "blue", "red"]);
console.log(set.has("red")); // → true (very fast!)
console.log(set.size);       // → 2 (duplicate removed automatically)
</code></pre>
<blockquote>
<p><strong>💡 Performance Note</strong></p>
<p>Checking if a value exists in an Array takes longer as the array grows. A Set checks in constant time — it's just as fast whether it has 10 items or 10 million. For membership checks on large data, always prefer Set.</p>
</blockquote>
<h2><strong>When to Use Map and Set</strong></h2>
<p>Still unsure which to pick? Here are the most common real-world scenarios:</p>
<p>🗺️ <strong>Use Map when…</strong><br />You need to store key-value pairs and your keys are not just simple strings. Example: counting how many times each word appears in a text, or caching data with object keys.</p>
<p>🎯<strong>Use Set when…</strong><br />You want a collection of unique items. Example: tracking which users have already seen a notification, or removing duplicate tags from a list.</p>
<p>📦<strong>Stick with Object when…</strong><br />You're modelling a "thing" with known properties, like a user profile: <code>{ name: "Alice", age: 25 }</code>. Objects are also required when working with JSON.</p>
<p>📋<strong>Stick with Array when…</strong><br />Order matters, duplicates are expected, or you need to use powerful methods like <code>.map()</code>, <code>.filter()</code>, or <code>.sort()</code>.</p>
<h3><strong>Real-world example — Word Counter</strong></h3>
<p>Here's a practical use of Map to count how many times each word appears in a sentence:</p>
<pre><code class="language-javascript">const sentence = "the cat sat on the mat and the cat";
const words = sentence.split(" ");
const counter = new Map();

words.forEach(word =&gt; {
  const count = counter.get(word) || 0;
  counter.set(word, count + 1);
});

console.log(counter.get("the")); // → 3
console.log(counter.get("cat")); // → 2
</code></pre>
<h3><strong>Real-world example — Unique Visitors</strong></h3>
<p>And here's Set in action, tracking unique page visitors:</p>
<pre><code class="language-javascript">const visited = new Set();

function trackVisit(userId) {
  visited.add(userId);
  console.log(`Total unique visitors: ${visited.size}`);
}

trackVisit("alice");   // → Total unique visitors: 1
trackVisit("bob");     // → Total unique visitors: 2
trackVisit("alice");   // → Total unique visitors: 2 (alice already counted!)
trackVisit("charlie"); // → Total unique visitors: 3
</code></pre>
<h3><strong>Quick Summary</strong></h3>
<table>
<thead>
<tr>
<th><strong>Structure</strong></th>
<th><strong>Stores</strong></th>
<th><strong>Unique?</strong></th>
<th><strong>Key Type</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Map</strong></td>
<td>Key-value pairs</td>
<td>Keys are unique</td>
<td>Any type</td>
</tr>
<tr>
<td><strong>Set</strong></td>
<td>Single values</td>
<td>All values unique</td>
<td>N/A</td>
</tr>
<tr>
<td><strong>Object</strong></td>
<td>Key-value pairs</td>
<td>Keys are unique</td>
<td>Strings only</td>
</tr>
<tr>
<td><strong>Array</strong></td>
<td>Ordered values</td>
<td>Duplicates allowed</td>
<td>Index (number)</td>
</tr>
</tbody></table>
<p>HaPPy CoDiN</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the "this" Keyword]]></title><description><![CDATA[If you've ever seen this in JavaScript code and thought "What on earth is that?" — you're not alone. It confuses almost every beginner. But once you understand one simple idea, it all clicks.

💡 The ]]></description><link>https://anilkambarweb.hashnode.dev/understanding-the-this-keyword</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/understanding-the-this-keyword</guid><category><![CDATA[this keyword JavaScript]]></category><category><![CDATA[this keyword]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Web Dev 2026]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 26 Apr 2026 08:19:52 GMT</pubDate><content:encoded><![CDATA[<p>If you've ever seen <code>this</code> in JavaScript code and thought <em>"What on earth is that?"</em> — you're not alone. It confuses almost every beginner. But once you understand one simple idea, it all clicks.</p>
<blockquote>
<p><strong>💡 The Golden Rule</strong><br /><code>this</code> <em>refers to whoever called the function. It's not about where the function is written — it's about who runs it.</em></p>
</blockquote>
<h2><strong>What Does</strong> <code>"this"</code> <strong>Actually Mean?</strong></h2>
<p>Think of <code>this</code> like the word <strong>"I"</strong> in a conversation. When <em>you</em> say "I am hungry," the word "I" refers to you. When your <em>friend</em> says it, "I" refers to your friend.</p>
<p>In JavaScript, <code>this</code> works the same way — it refers to the <strong>object that is currently using the function</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/9812b3c2-92cd-47a6-b4bc-da2a90a302e0.png" alt="" style="display:block;margin:0 auto" />

<h2><code>"this"</code> <strong>in the Global Context</strong></h2>
<p>When you're not inside any object or function, <code>this</code> refers to the <strong>global object</strong>. But here's the thing — what that global object <em>is</em> depends on <strong>where your JavaScript is running</strong>.</p>
<p>There are two main environments where people run JavaScript:</p>
<p>🌐<strong>In the Browser:</strong> this = window<br />Running JS in Chrome, Firefox, Safari etc. The global object is called <code>window</code>.</p>
<p>🖥️<strong>In Node.js:</strong> this = globalThis / {}<br />Running JS on your computer via terminal. The global object is called <code>global</code>, not window.</p>
<h3><strong>🌐 In the Browser</strong></h3>
<p>The browser wraps everything in a giant object called <code>window</code>. At the global level, <code>this</code> and <code>window</code> are the exact same thing.</p>
<p>Browser — global scope (open DevTools → Console and try this)</p>
<pre><code class="language-javascript">// At the very top of your script (not inside anything)
console.log(this);           // → Window { alert: f, ... }
console.log(this === window); // → true  (they are the same!)

// Setting a property on "this" is the same as setting it on window
this.myName = "JavaScript";
console.log(window.myName);  // → "JavaScript"
</code></pre>
<h3><strong>🖥️ In Node.js</strong></h3>
<p>Node.js is a way to run JavaScript on your computer (outside the browser), commonly used for backend code. Here, there's no <code>window</code> — instead the global object is called <code>global</code>. But there's also a quirk: at the top level of a Node.js <em>file</em>, <code>this</code> is actually an empty object <code>{}</code>, not <code>global</code>.</p>
<p>Node.js — global scope (run with: node index.js)</p>
<pre><code class="language-javascript">// Top of a .js file in Node.js
console.log(this);            // → {}  (empty object — a Node quirk!)
console.log(this === global); // → false  (surprising!)

// But inside a regular function in Node, this IS global:
function test() {
  console.log(this === global); // → true
}
test();
</code></pre>
<h3><strong>The Safe, Universal Way —</strong> <code>globalThis</code></h3>
<p>Because the global object has different names in different environments, JavaScript introduced <code>globalThis</code> — a single keyword that works <strong>everywhere</strong>, whether you're in a browser or Node.js.</p>
<p>Works in both Browser AND Node.js</p>
<pre><code class="language-javascript">// globalThis always points to the global object — everywhere
console.log(globalThis); // → Window { ... }  in browser
                         // → Object [global] in Node.js

// Use globalThis when you're writing code for both environments
globalThis.appName = "My App";
console.log(globalThis.appName); // → "My App"  ✓ works everywhere
</code></pre>
<blockquote>
<p><strong>📌 Remember:</strong> <code>this</code> <em>at the global level = the "owner" of everything. In a</em> <strong>browser</strong> <em>it's</em> <code>window</code><em>, in</em> <strong>Node.js</strong> <em>it's</em> <code>global</code> <em>(with a quirk at file-top level). When in doubt, use</em> <code>globalThis</code> <em>— it works everywhere.</em></p>
</blockquote>
<h2><code>"this"</code> <strong>Inside an Object</strong></h2>
<p>This is where <code>this</code> becomes really useful. When a function lives inside an object (called a <strong>method</strong>), <code>this</code> refers to that object.</p>
<pre><code class="language-javascript">const person = {
  name: "Alice",
  age: 25,

  greet: function() {
    // Who called greet()? → the "person" object
    // So "this" here is "person"
    console.log("Hi, I am " + this.name);
  }
};

person.greet(); // → "Hi, I am Alice"
//  ↑ person is the caller, so this = person
</code></pre>
<p>Since <code>person</code> called <code>greet()</code>, <code>this</code> inside <code>greet</code> is <code>person</code>. So <a href="http://this.name"><code>this.name</code></a> gives us <code>"Alice"</code>.</p>
<h3><strong>Another example — accessing multiple properties</strong></h3>
<pre><code class="language-javascript">const car = {
  brand: "Toyota",
  model: "Corolla",

  describe: function() {
    console.log("This car is a " + this.brand + " " + this.model);
  }
};

car.describe(); // → "This car is a Toyota Corolla"
</code></pre>
<h2><code>"this"</code> <strong>Inside a Regular Function</strong></h2>
<p>When you call a function <em>on its own</em> (not as part of an object), <code>this</code> defaults to the <strong>global object</strong> — or <code>undefined</code> in strict mode.</p>
<pre><code class="language-javascript">function sayHello() {
  console.log(this); // → Window (in a browser)
}

sayHello(); // No object before the dot → this = global/window

// In strict mode:
"use strict";
function strictHello() {
  console.log(this); // → undefined
}
strictHello();
</code></pre>
<blockquote>
<p><strong>⚠️ Watch out:</strong> <em>No caller before the dot? Then</em> <code>this</code> <em>is the global window. This can cause unexpected bugs if you're not careful!</em></p>
</blockquote>
<h2><strong>How the Calling Context Changes</strong> <code>"this"</code></h2>
<p>Here's the twist — the <em>same function</em> can have a <em>different</em> <code>this</code> depending on <strong>how it's called</strong>. This is the part that trips up most beginners.</p>
<p>JavaScript — same function, different callers</p>
<pre><code class="language-javascript">function introduce() {
  console.log("My name is " + this.name);
}

const alice = { name: "Alice", introduce: introduce };
const bob   = { name: "Bob",   introduce: introduce };

alice.introduce(); // → "My name is Alice"  (this = alice)
bob.introduce();   // → "My name is Bob"    (this = bob)

introduce();       // → "My name is undefined" (this = window/global)
</code></pre>
<p>The function <code>introduce</code> is identical in all three cases. But <code>this</code> changes based on who's calling it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/9383766b-3082-46bc-b397-47f9e1e3f126.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>All Contexts at a Glance</strong></h2>
<p>Here's every context where <code>this</code> can appear, and what it equals:</p>
<p>🌍<strong>Global Scope:</strong> this = window<br />Top-level code, outside of any function or object.  </p>
<p>🧱<strong>Object Method:</strong> this = the object<br />A function called as a property of an object.</p>
<p>🔧<strong>Regular Function:</strong> this = window<br />A function called on its own, with no object before it.  </p>
<p>⚡<strong>Strict Mode:</strong> this = undefined<br />Inside a regular function when "use strict" is active.</p>
<h3><strong>The Cheat Sheet</strong></h3>
<table>
<thead>
<tr>
<th>Where you write code</th>
<th>How it's called</th>
<th>"this" equals</th>
</tr>
</thead>
<tbody><tr>
<td>Top of the file</td>
<td>—</td>
<td>window</td>
</tr>
<tr>
<td>Inside an object</td>
<td><code>obj.method()</code></td>
<td>obj</td>
</tr>
<tr>
<td>Standalone function</td>
<td><code>myFunc()</code></td>
<td>window</td>
</tr>
<tr>
<td>Strict mode function</td>
<td><code>myFunc()</code></td>
<td>undefined</td>
</tr>
</tbody></table>
<h3><strong>The One Thing to Remember</strong></h3>
<p>When you're confused about <code>this</code>, just ask yourself one question:</p>
<blockquote>
<p>**❓ Who is calling this function?<em>*<em>Whatever is to the left of the dot before the function call — that's</em> <code>this</code>*. No dot? Then</em> <code>this</code> <em>is the window (or undefined in strict mode).</em></p>
</blockquote>
<p>That's it! As you keep practicing with objects and functions, <code>this</code> will become second nature. Happy coding!</p>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[Understanding Promises in JavaScript]]></title><description><![CDATA[Imagine you’re at a busy burger joint. You place your order, and instead of making you stand at the counter staring at the grill, the cashier hands you a buzzer.
That buzzer is a Promise. It represent]]></description><link>https://anilkambarweb.hashnode.dev/understanding-promises-in-javascript</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/understanding-promises-in-javascript</guid><category><![CDATA[new Promise()]]></category><category><![CDATA[resolve]]></category><category><![CDATA[reject]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Web Dev 2026]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 26 Apr 2026 06:42:21 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you’re at a busy burger joint. You place your order, and instead of making you stand at the counter staring at the grill, the cashier hands you a <strong>buzzer</strong>.</p>
<p>That buzzer is a <strong>Promise</strong>. It represents a value (your burger) that isn't ready yet, but will be available in the future. You can go sit down, check your phone, or chat with friends. When the buzzer goes off, you either get your meal (success!) or a notification that they ran out of ingredients (failure).</p>
<p>In JavaScript, Promises work exactly like that buzzer.</p>
<h2><strong>Why do we even need Promises?</strong></h2>
<p>JavaScript runs <strong>one thing at a time</strong>. But the real world isn't that simple. Imagine you're building a website that fetches a user's profile from a server. That request takes time — maybe half a second, maybe two seconds. If JavaScript just <em>waited</em> and did nothing, your whole page would freeze. That's awful.</p>
<blockquote>
<p>Think of ordering a coffee at a café. You place your order and the barista gives you a <strong>numbered ticket</strong>. You don't stand at the counter blocking everyone — you go sit down. When your number is called, you go pick up your coffee. That ticket is a <strong>Promise</strong>: it guarantees you'll get a result later.</p>
</blockquote>
<h3><strong>The old way: Callbacks</strong></h3>
<p>Before Promises, JavaScript used <strong>callbacks</strong> — functions you pass into other functions to be called when work is done. This works, but nesting callbacks inside callbacks inside callbacks creates something developers dread:</p>
<pre><code class="language-javascript">// Welcome to "Callback Hell"
getUser(1, function(user) {
  getOrders(user.id, function(orders) {
    getItems(orders[0].id, function(items) {
      getPrice(items, function(price) {
        // By now, we're 4 levels deep
        console.log(price);
      });
    });
  });
});
</code></pre>
<p>This shape — code drifting further and further to the right — is called <strong>"Callback Hell"</strong> or the <em>"Pyramid of Doom"</em>. It's hard to read, hard to debug, and hard to handle errors in. Promises were invented to fix this.</p>
<h2><strong>What is a Promise?</strong></h2>
<p>A Promise is an <strong>object</strong> that represents the eventual result of an asynchronous operation. It's a placeholder for a value that doesn't exist yet — a <em>future value</em>.</p>
<blockquote>
<p>Key Definition</p>
<p><em>A Promise says:</em> <em><strong>"I don't have the answer right now, but I promise I'll give you something — either a result or an error — when I'm done."</strong></em></p>
</blockquote>
<p>You create a Promise using <strong>new Promise()</strong>. Inside, you pass a function that receives two arguments: <strong>resolve (call this when successful) and reject (call this when something goes wrong)</strong>.</p>
<pre><code class="language-javascript">// Creating a Promise
const myPromise = new Promise(function(resolve, reject) {

  // Pretend we're fetching data from a server...
  const success = true;

  if (success) {
    resolve("✅ Here's your data!");  // it worked!
  } else {
    reject("❌ Something went wrong"); // it failed
  }

});
</code></pre>
<blockquote>
<p>Analogy recap</p>
<p><em>resolve = the barista calling your number. reject = the barista coming over to say "Sorry, we're out of that." Either way, you get an answer.</em></p>
</blockquote>
<h2><strong>The three states of a Promise</strong></h2>
<p>Every Promise lives in exactly <strong>one of three states</strong> at any given moment. Think of it like a package you ordered online:</p>
<p>⏳Pending: The operation is still in progress. No result yet — like your package "in transit."</p>
<p>✅Fulfilled: <code>resolve()</code> was called. The operation completed successfully — package delivered!</p>
<p>❌ Rejected: <code>reject()</code> was called. Something went wrong — package lost in transit.</p>
<p><em>Once a Promise moves from</em> <em><strong>Pending</strong></em> <em>to either Fulfilled or Rejected, it</em> <em><strong>cannot change again</strong></em><em>. A delivered package can't go back to being "in transit."</em></p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/caf88314-a693-40f2-9bcc-df6b300d1883.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Handling success and failure</strong></h2>
<p>Once you have a Promise, you need to tell JavaScript <strong>what to do when it finishes</strong>. You do this with three methods:</p>
<ul>
<li><p>.then()— runs when the Promise is<strong>fulfilled</strong>(success)</p>
</li>
<li><p>.catch()— runs when the Promise is<strong>rejected</strong>(failure)</p>
</li>
<li><p>.finally()— runs<strong>always</strong>, whether it succeeded or failed</p>
</li>
</ul>
<pre><code class="language-javascript">const fetchUser = new Promise(function(resolve, reject) {
  // Simulate a 1-second network request
  setTimeout(function() {
    const userFound = true;

    if (userFound) {
      resolve({ name: "Aisha", age: 28 });
    } else {
      reject("User not found");
    }
  }, 1000);
});

fetchUser
  .then(function(user) {
    // ✅ This runs if the Promise resolved
    console.log("Got the user:", user.name); // "Aisha"
  })
  .catch(function(error) {
    // ❌ This runs if the Promise rejected
    console.log("Error:", error);
  })
  .finally(function() {
    // 🏁 This ALWAYS runs — great for cleanup
    console.log("Request finished.");
  });
</code></pre>
<blockquote>
<p>Think of it like...</p>
<p><em>You send a text asking your friend to pick you up. .then() = they say "On my way!" .catch() = they say "Sorry, can't make it." .finally() = you put your phone back in your pocket regardless.</em></p>
</blockquote>
<h2><strong>Callbacks vs Promises</strong></h2>
<p>Let's look at the <strong>same task</strong> — get a user, then get their posts — written both ways. See how much easier Promises are to read.</p>
<p><strong>With Callbacks</strong></p>
<pre><code class="language-javascript">// Nested callbacks — hard to follow
getUser(42, function(err, user) {
  if (err) {
    console.log("Error getting user");
    return;
  }
  getPosts(user.id, function(err, posts) {
    if (err) {
      console.log("Error getting posts");
      return;
    }
    getComments(posts[0].id, function(err, comments) {
      if (err) {
        console.log("Error getting comments");
        return;
      }
      // Finally! 3 levels deep, error check everywhere
      console.log(comments);
    });
  });
});
</code></pre>
<p><strong>With Promises</strong></p>
<pre><code class="language-javascript">// Clean chain — reads top to bottom, one .catch()
getUser(42)
  .then(function(user) {
    return getPosts(user.id);  // return passes the value along
  })
  .then(function(posts) {
    return getComments(posts[0].id);
  })
  .then(function(comments) {
    console.log(comments);       // Yoy get final answer here
  })
  .catch(function(err) {
    // ONE catch handles errors from ALL steps above
    console.log("Something went wrong:", err);
  });
</code></pre>
<p><strong>Why Promises win</strong></p>
<ul>
<li><p><strong>Flat, readable code</strong>— no more pyramid shape drifting to the right</p>
</li>
<li><p><strong>One error handler</strong>— a single.catch()handles errors from every step</p>
</li>
<li><p><strong>Easy to extend</strong>— just add another.then()to the chain</p>
</li>
<li><p><strong>Composable</strong>— you can combine, race, or run Promises in parallel</p>
</li>
</ul>
<h2><strong>Promise chaining</strong></h2>
<p>One of the most powerful features of Promises is <strong>chaining</strong>. Each .then() can return a value (or a new Promise), which gets passed to the next .then() in the chain — like an assembly line where each station hands off to the next.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/5f08cd6e-0d75-47fb-9064-84cf4da4385b.png" alt="" style="display:block;margin:0 auto" />

<pre><code class="language-javascript">// A real-world-style chain: log in → get profile → show dashboard

login("aisha@example.com", "password123")
  .then(token =&gt; {
    console.log("Logged in! Token received.");
    return getProfile(token);
  })
  .then(profile =&gt; {
    console.log("Welcome,", profile.name);
    return getDashboard(profile.id);
  })
  .then(dashboard =&gt; {
    console.log("Dashboard loaded:", dashboard);
  })
  .catch(error =&gt; {
    console.log("Oops! Something failed:", error);
  })
  .finally(() =&gt; {
    hideLoadingSpinner();
  });
</code></pre>
<blockquote>
<p>⚠️ Common beginner mistake</p>
<p><em>Don't forget to</em> <em><strong>return</strong></em> <em>inside .then()! If you forget the return, the next .then() won't receive the value — it'll get undefined instead. Always return the Promise or value you want to pass along.</em></p>
</blockquote>
<h2><strong>RECAP</strong></h2>
<h3><strong>You now understand Promises</strong></h3>
<ul>
<li><p>Promises solve <strong>Callback Hell</strong> — they flatten nested async code into a readable chain.</p>
</li>
<li><p>A Promise is a <strong>placeholder for a future value</strong> — it says "I'll give you an answer later."</p>
</li>
<li><p>Every Promise is in one of three states: <strong>Pending</strong>, <strong>Fulfilled</strong>, or <strong>Rejected</strong>.</p>
</li>
<li><p>Use <code>.then()</code> for success, <code>.catch()</code> for errors, and <code>.finally()</code> for cleanup.</p>
</li>
<li><p><strong>Chain</strong> multiple <code>.then()</code> calls — and always <strong>return</strong> values to pass them along.</p>
</li>
<li><p>One <code>.catch()</code> at the end protects your entire chain from errors.</p>
</li>
</ul>
<h2><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></h2>
]]></content:encoded></item><item><title><![CDATA[Async Code in Node.js: Callbacks and Promises]]></title><description><![CDATA[If you are just starting with Node.js, you’ve likely heard the term "Asynchronous" (or async). It sounds fancy, but it is actually the secret sauce that makes Node.js so fast.
In this guide, we’ll bre]]></description><link>https://anilkambarweb.hashnode.dev/async-code-in-node-js-callbacks-and-promises</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/async-code-in-node-js-callbacks-and-promises</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[Async Code in Node.js: Callbacks and Promises]]></category><category><![CDATA[Web Dev 2026]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sat, 25 Apr 2026 11:32:47 GMT</pubDate><content:encoded><![CDATA[<p>If you are just starting with Node.js, you’ve likely heard the term <strong>"Asynchronous"</strong> (or async). It sounds fancy, but it is actually the secret sauce that makes Node.js so fast.</p>
<p>In this guide, we’ll break down why we need it and how to master the two most common ways to handle it: <strong>Callbacks</strong> and <strong>Promises</strong>.</p>
<h2><strong>Why does async code even exist?</strong></h2>
<p>Imagine you walk into a coffee shop and place your order. The barista doesn't freeze in place, staring at the espresso machine until your drink is ready — they call your name when it's done, and in the meantime they take everyone else's orders too.</p>
<p>Node.js works exactly the same way. It runs on a <em>single thread</em>, meaning it can only do one thing at a time. If it had to wait — fully stopped — every time it read a file from disk or fetched data from a database, your entire program would grind to a halt. Nobody else's request would be processed. That's terrible.</p>
<blockquote>
<p><strong>Key idea</strong></p>
<p>Asynchronous (async) code lets Node.js <em>start</em> a slow task (like reading a file), move on to other work, and come back to handle the result when it's ready — without blocking everything else.</p>
</blockquote>
<p>Reading a file is the classic example. Let's use it throughout this post. When you ask Node.js to read a file, it hands the job to the operating system and immediately moves on. When the OS finishes, it taps Node.js on the shoulder: <em>"Hey, here's your file content."</em></p>
<p>The question is: <strong>how do you tell Node.js what to do when that tap on the shoulder arrives?</strong> That's where callbacks and promises come in.</p>
<h2><strong>Callbacks — the original approach</strong></h2>
<p>A <strong>callback</strong> is just a function you hand to another function, saying: <em>"When you're done, call this."</em> That's literally it. You're passing your "what to do next" instructions as a piece of code.</p>
<p>Here's the most common example in Node.js — reading a file:</p>
<pre><code class="language-javascript">const fs = require('fs');

// Start reading the file — don't wait around.
// When it's done, call the function we pass in.
fs.readFile('hello.txt', 'utf8', function(err, data) {
  // This function IS the callback.
  // Node.js calls it once the file is ready.

  if (err) {
    console.log('Something went wrong:', err);
    return;
  }

  console.log('File contents:', data);
});

// This runs IMMEDIATELY — before the file is even read!
console.log('Started reading the file...');
</code></pre>
<p>Notice something surprising: the last <code>console.log</code> prints <em>before</em> the file content does, even though it appears later in the code. That's async in action — Node.js fires off the file read, then immediately continues to the next line.</p>
<h3><strong>Step-by-step: what actually happens</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/0c76c1bb-e211-4588-bcb5-f555954b41d8.png" alt="" style="display:block;margin:0 auto" />

<p>The two important rules of the Node.js callback pattern:</p>
<ol>
<li><p><strong>Error first.</strong> The callback's first argument is always an error object (<code>err</code>). If nothing went wrong, it's <code>null</code>. Always check it.</p>
</li>
<li><p><strong>Data second.</strong> The actual result — your file content, your database rows — comes in the second argument.</p>
</li>
</ol>
<h2><strong>The problem: Callback Hell</strong></h2>
<p>Callbacks work fine for a single operation. But real programs rarely do just one thing. You often need to do things <em>in sequence</em> — read a config file, then connect to a database using that config, then run a query, then write the result to a log file.</p>
<p>With callbacks, each step has to live <em>inside</em> the previous step's callback. This creates nesting — and it spirals out of control fast.</p>
<p>example for callback hell — nested callbacks</p>
<pre><code class="language-javascript">fs.readFile('config.json', 'utf8', function(err, config) {
  if (err) { return console.log('Error reading config'); }

  db.connect(config, function(err, connection) {
    if (err) { return console.log('Error connecting'); }

    connection.query('SELECT * FROM users', function(err, rows) {
      if (err) { return console.log('Error querying'); }

      fs.writeFile('log.txt', rows, function(err) {
        if (err) { return console.log('Error writing'); }

        console.log('All done!'); // 5 levels deep 😱
      });
    });
  });
});
</code></pre>
<blockquote>
<p><strong>The problem</strong></p>
<p>This "pyramid of doom" is hard to read, hard to debug, and every single step needs its own error check copied and pasted. Add one more step and you're six levels deep. This is officially called<strong>Callback Hell</strong>.</p>
</blockquote>
<h2><strong>Promises — the better way</strong></h2>
<p>A <strong>Promise</strong> is an object that represents a value you don't have <em>yet</em> — but will have eventually. Think of it like a ticket at a restaurant. They give you the ticket now; you'll get your food later. You can plan around having the ticket without knowing exactly when the food arrives.</p>
<p>A Promise is always in one of three states:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/8ab4f393-f459-4274-8797-9121f9bfd56a.png" alt="" style="display:block;margin:0 auto" />

<p>Now here's how you use a Promise. The <code>fs/promises</code> module gives you a version of <code>readFile</code> that returns a Promise instead of using a callback.</p>
<p>Reading a file with a promise:</p>
<pre><code class="language-javascript">const fs = require('fs/promises'); // The promise-based version

fs.readFile('hello.txt', 'utf8')
  .then(function(data) {
    // This runs when it succeeds ✓
    console.log('File contents:', data);
  })
  .catch(function(err) {
    // This runs if something goes wrong ✗
    console.log('Error:', err);
  });
</code></pre>
<p>Already cleaner — one <code>.then()</code> for success, one <code>.catch()</code> for all errors. But the real superpower is <strong>chaining</strong>. Each <code>.then()</code> returns a new Promise, so you can chain steps in a flat, readable line:</p>
<p>Promise chaining — no pyramid of doom</p>
<pre><code class="language-javascript">fs.readFile('config.json', 'utf8')
  .then(config =&gt; db.connect(config))
  .then(connection =&gt; connection.query('SELECT * FROM users'))
  .then(rows =&gt; fs.writeFile('log.txt', rows))
  .then(() =&gt; console.log('All done!'))
  .catch(err =&gt; console.log('Something failed:', err));
  // One .catch() handles errors from ALL steps above ✓
</code></pre>
<blockquote>
<p><strong>Much better</strong></p>
<p>Same four steps as the callback version — but flat, readable, and with a <em>single</em> error handler catching problems from any step. This is the power of Promise chaining.</p>
</blockquote>
<h2><strong>Callbacks vs Promises — at a glance</strong></h2>
<h4><strong>Callbacks</strong></h4>
<ul>
<li><p>Gets deeply nested fast</p>
</li>
<li><p>Error handling repeated at every step</p>
</li>
<li><p>Hard to read top-to-bottom</p>
</li>
<li><p>Hard to debug</p>
</li>
</ul>
<h4><strong>Promises</strong></h4>
<ul>
<li><p>Stays flat with chaining</p>
</li>
<li><p>One .catch() handles all errors</p>
</li>
<li><p>Reads like a to-do list</p>
</li>
<li><p>Easier to trace and debug</p>
</li>
</ul>
<h3><strong>Bonus: async/await — Promises, but even nicer</strong></h3>
<p>Promises are great, but there's a syntax sugar on top of them called <code>async/await</code> that makes your code look almost like normal, synchronous code — while still being fully async underneath.</p>
<p>async/await — the modern way (still uses promises!)</p>
<pre><code class="language-javascript">async function doEverything() {
  try {
    const config     = await fs.readFile('config.json', 'utf8');
    const connection = await db.connect(config);
    const rows       = await connection.query('SELECT * FROM users');
    await fs.writeFile('log.txt', rows);
    console.log('All done!');
  } catch (err) {
    console.log('Something failed:', err);
  }
}

doEverything();
</code></pre>
<blockquote>
<p><strong>Remember</strong><code>async/await</code> is not a replacement for Promises — it's built on top of them. Every <code>await</code> is just a nicer way to write <code>.then()</code>. Under the hood, it's all Promises.</p>
</blockquote>
<h2><strong>Quick recap</strong></h2>
<p><strong>Async code exists</strong> because Node.js runs on one thread and can't afford to sit and wait for slow operations like file reads or database calls.</p>
<p><strong>Callbacks</strong> were the first solution — you pass a function to be called when the work is done. They work, but they nest badly and make error handling messy.</p>
<p><strong>Promises</strong> solve callback hell by returning an object you can chain with <code>.then()</code> and catch all errors with a single <code>.catch()</code>.</p>
<p><strong>async/await</strong> is modern Promise syntax that makes async code look like plain, readable, step-by-step instructions.</p>
<blockquote>
<p><strong>Where to go next</strong></p>
<p>Try writing a small Node.js script that reads a text file and prints its contents. Start with the callback version, then rewrite it using Promises, then try async/await. Seeing the three styles side by side will make everything click.</p>
</blockquote>
<h2><strong><mark class="bg-yellow-200 dark:bg-yellow-500/30">HaPPy CoDiNg</mark></strong></h2>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[If you’ve been diving into JavaScript, you might have noticed code that looks like a shortcut or a "secret handshake." You see curly braces {} or brackets [] on the left side of an equal sign, and sud]]></description><link>https://anilkambarweb.hashnode.dev/destructuring-in-javascript</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/destructuring-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[destructuring in JavaScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[webdevelopment]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Mon, 20 Apr 2026 17:26:46 GMT</pubDate><content:encoded><![CDATA[<p>If you’ve been diving into JavaScript, you might have noticed code that looks like a shortcut or a "secret handshake." You see curly braces <code>{}</code> or brackets <code>[]</code> on the left side of an equal sign, and suddenly variables are being created out of thin air.</p>
<p>That "magic" is called <strong>destructuring</strong>. Don't let the name intimidate you—it’s actually one of the best tools for making your code cleaner and easier to read.</p>
<h2><strong>What is destructuring?</strong></h2>
<p>Imagine you received a gift box with multiple items inside. Instead of saying "the box" every time you want something from it, you take each item out and give it its own label. That's exactly what <strong>destructuring</strong> does in JavaScript — it lets you pull values out of an array or object and assign them to variables, all in one line.</p>
<blockquote>
<p><strong>Simple definition:</strong> Destructuring is a shorthand way to extract values from arrays or objects into separate, named variables.</p>
</blockquote>
<p>Before destructuring was added to JavaScript, you had to do things the long way. Destructuring makes the same task clean and readable.</p>
<h2><strong>Destructuring arrays</strong></h2>
<p>With an array, values are ordered by position. When you destructure, you pick values out by their position — left to right.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/9d95a3e7-e508-487a-b50e-3f975410b0b7.png" alt="" style="display:block;margin:0 auto" />

<p>Here is how this looks in actual code:</p>
<p><strong>Before Destructure method:</strong></p>
<pre><code class="language-javascript">const colors = [
  "red",
  "green",
  "blue"
];

const first = colors[0];
const second = colors[1];
const third = colors[2];
</code></pre>
<p><strong>After Destructure method:</strong></p>
<pre><code class="language-javascript">const colors = [
  "red",
  "green",
  "blue"
];

const [first, second, third]
  = colors;

// Done! ✓
</code></pre>
<blockquote>
<p>You can skip positions you don't need by using a comma with no variable name. For example: <code>const [, second] = colors</code> gives you only the second item.</p>
</blockquote>
<h2><strong>Destructuring objects</strong></h2>
<p>Objects are different — they store values with named <em>keys</em>. When you destructure an object, you use those same key names inside curly braces <code>{ }</code> to pull values out.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/6055478d-a44f-4ec5-9f1b-66e659de2ae5.png" alt="" style="display:block;margin:0 auto" />

<p>**<br />Object without destructuring**</p>
<pre><code class="language-javascript">const user = {
  name: "Alice",
  age: 28,
  city: "Lagos"
};

const name = user.name;
const age = user.age;
const city = user.city;
</code></pre>
<p><strong>Object with destructuring</strong></p>
<pre><code class="language-javascript">const user = {
  name: "Alice",
  age: 28,
  city: "Lagos"
};

const { name, age, city }
  = user;

// Done! ✓
</code></pre>
<p>You can also rename variables while destructuring — useful when a key name is too generic:</p>
<pre><code class="language-javascript">const { name: userName, city: userCity } = user;

// name is now accessible as userName
// city is now accessible as userCity
</code></pre>
<h2><strong>Default values</strong></h2>
<p>Sometimes a value might not exist in the object or array. Instead of getting <code>undefined</code>, you can set a <em>default value</em> that will be used as a fallback.</p>
<p><strong>Default values in objects</strong></p>
<pre><code class="language-javascript">const user = {
  name: "Alice"
  // 'role' is missing here
};

const { name, role = "viewer" } = user;

console.log(name); // "Alice"
console.log(role); // "viewer" (the default)
</code></pre>
<p><strong>Default values in arrays</strong></p>
<pre><code class="language-javascript">const scores = [95];

const [first = 0, second = 0] = scores;

console.log(first); // 95
console.log(second); // 0 (default, no value at [1])
</code></pre>
<blockquote>
<p><strong>Key rule:</strong> Default values are only used when the value is <code>undefined</code>. If the property exists but is <code>null</code> or <code>false</code>, the default will NOT be applied.</p>
</blockquote>
<h2><strong>Benefits of destructuring</strong></h2>
<p>Now that you've seen how it works, here's why developers love using destructuring in their everyday code:</p>
<p><strong>Less repetition:</strong> No more writing <a href="http://user.name"><code>user.name</code></a>, <code>user.age</code>, <a href="http://user.city"><code>user.city</code></a> repeatedly. Extract once, use freely.</p>
<p><strong>Cleaner, readable code:</strong> Your intent is clearer. Readers immediately see what values you care about.</p>
<p><strong>Safer defaults:</strong> Set fallback values to avoid unexpected <code>undefined</code> bugs in your app.</p>
<p><strong>Great for functions:</strong> Destructure function parameters directly to make function signatures expressive and short.</p>
<p>Here's a real-world example — destructuring inside a function parameter:</p>
<pre><code class="language-javascript">// Without destructuring
function greet(user) {
  console.log("Hi, " + user.name);
}

// With destructuring ✓
function greet({ name, city = "Unknown" }) {
  console.log(`Hi, \({name} from \){city}`);
}

greet({ name: "Alice", city: "Lagos" });
// Hi, Alice from Lagos
</code></pre>
<blockquote>
<p><strong>Quick recap:</strong> Destructuring lets you unpack values from arrays (by position) and objects (by key name) into clean, reusable variables — with optional default values and renaming on the fly.</p>
</blockquote>
<p><strong>Happy Coding</strong></p>
]]></content:encoded></item><item><title><![CDATA[Synchronous vs Asynchronous JavaScript]]></title><description><![CDATA[Imagine you're at a coffee shop. If the barista takes your order, makes your latte while you stand at the counter, and refuses to talk to the next person until your drink is done — that's synchronous.]]></description><link>https://anilkambarweb.hashnode.dev/synchronous-vs-asynchronous-javascript</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/synchronous-vs-asynchronous-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[syncvsasync]]></category><category><![CDATA[synchronous]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[WebDevCohort2026]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 19 Apr 2026 18:44:29 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you're at a coffee shop. If the barista takes your order, makes your latte while you stand at the counter, and refuses to talk to the next person until your drink is done — that's synchronous. If the barista takes your order, gives you a buzzer, and moves on to the next customer while the espresso machine runs — that's asynchronous.</p>
<p>In JavaScript, how we handle these "orders" can make the difference between a smooth app and one that feels broken. Every time your app fetches data, waits for a timer, or reads a file, it's placing an "order." The question is: does your program freeze at the counter, or does it keep serving other customers while it waits?</p>
<h2>What is synchronous code?</h2>
<p>Imagine you're following a recipe. You read step one, complete it, then move to step two, then step three — one at a time, in order. That's exactly how <strong>synchronous code</strong> works.</p>
<blockquote>
<p><strong>Real-world analogy</strong><br />Think of a single cashier at a store. She serves Customer A completely — scans every item, takes payment, prints the receipt — <em>before</em> even looking at Customer B. The line waits. Nothing moves until the current task is fully done.</p>
</blockquote>
<p>In JavaScript, synchronous code runs <strong>line by line</strong>. The program reads your code from top to bottom and executes each instruction before moving to the next one.</p>
<pre><code class="language-javascript">console.log("Step 1: Boil water");
console.log("Step 2: Add tea bag");
console.log("Step 3: Pour into cup");

//Output (always in this exact order):
Step 1: Boil water
Step 2: Add tea bag
Step 3: Pour into cup
</code></pre>
<blockquote>
<p><strong>Key idea</strong><br />In synchronous code, each line <strong>waits</strong> for the previous one to finish before it runs. The order is predictable and easy to follow.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/50987511-f233-49c4-82bb-1610920b11d8.png" alt="" style="display:block;margin:0 auto" />

<h2>What is asynchronous code?</h2>
<p><strong>Asynchronous code</strong> allows JavaScript to start a task, move on to other work, and come back to handle the result later — when it's ready.</p>
<blockquote>
<p><strong>Real-world analogy</strong><br />Think of a waiter at a restaurant. He takes Customer A's order, sends it to the kitchen, and <em>immediately</em> moves on to take Customer B's order. When the kitchen is done with Customer A's food, they signal the waiter, and he delivers it. Nobody just stands around waiting.</p>
</blockquote>
<p>This is incredibly useful when a task takes time — like fetching data from the internet, reading a file, or waiting for a timer. Instead of freezing everything, JavaScript keeps working.</p>
<pre><code class="language-javascript">console.log("I run FIRST");

setTimeout(function() {
  console.log("I run THIRD (after 2 seconds)");
}, 2000); // wait 2 seconds, then run

console.log("I run SECOND");

// Output:
// I run FIRST
// I run SECOND
// I run THIRD (after 2 seconds)
</code></pre>
<blockquote>
<p><strong>Key idea</strong><br />Asynchronous code doesn't block the rest of your program. While one task waits (e.g. a timer, a network request), <strong>everything else keeps running</strong>.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/d4c36ad1-9f5f-4e89-aaf4-3aef6fbfef6e.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Why Does JavaScript Need Async?</strong></h2>
<p>JavaScript was originally built for browsers, and browsers do <strong>one thing at a time</strong> on the main thread. If JavaScript is busy running code, <em>nothing else can happen</em> — no scrolling, no button clicks, no animations.</p>
<p><strong>But many real-world tasks take time:</strong></p>
<h4><strong>⏳ Slow operations</strong></h4>
<ul>
<li><p>Fetching data from an API server</p>
</li>
<li><p>Reading a file from disk</p>
</li>
<li><p>Querying a database</p>
</li>
<li><p>Waiting for a timer to expire</p>
</li>
<li><p>Uploading or downloading files</p>
</li>
</ul>
<h4><strong>⚡ What async enables</strong></h4>
<ul>
<li><p>Page stays responsive while loading</p>
</li>
<li><p>Buttons still work during network calls</p>
</li>
<li><p>Animations don't freeze</p>
</li>
<li><p>Multiple requests can run in parallel</p>
</li>
<li><p>Better user experience overall</p>
</li>
</ul>
<h2><strong>Async in the Wild — API Calls &amp; Timers</strong></h2>
<p><strong>Example 1 — Fetching data from an API</strong></p>
<p>When your app needs to load user data from a server, it would be catastrophic to freeze the browser while waiting. This is the most common real-world use of async JavaScript.</p>
<pre><code class="language-javascript">async function getUser() {
  console.log("1. Starting to fetch user...");

  // await pauses THIS function, but not the whole page
  const response = await fetch('https://api.example.com/user/1');
  const user = await response.json();

  console.log("3. Got user:", user.name);
}

getUser(); // starts fetching in background
console.log("2. This runs WHILE data is loading");

// Output:
// 1. Starting to fetch user...
// 2. This runs WHILE data is loading
// 3. Got user: Alice
</code></pre>
<blockquote>
<p><strong>What's happening here?</strong><br />The <code>await</code> keyword tells JavaScript: "wait for this, but let other code keep running in the meantime." The page stays interactive the entire time.</p>
</blockquote>
<p><strong>Example 2 — Timers</strong></p>
<p>The simplest example of async behavior is <code>setTimeout</code>. It schedules a function to run later, without stopping anything else.</p>
<pre><code class="language-javascript">console.log("Page loaded!");

// Show a welcome message after 3 seconds
setTimeout(() =&gt; {
  console.log("Welcome! Thanks for visiting.");
}, 3000);

console.log("User can interact with the page now.");

// The user never waits — the message just appears later
</code></pre>
<h2><strong>Problems With Blocking Code</strong></h2>
<p>When code runs synchronously and takes a long time, it blocks everything else. This is called <em>blocking code</em>, and it makes your app feel broken.</p>
<blockquote>
<p><strong>⚠ What blocking looks like to a user</strong></p>
<p>The browser freezes. Buttons stop responding. The page can't scroll. Animations stutter. It feels like the app has crashed — even though it's technically still running.</p>
</blockquote>
<pre><code class="language-javascript">console.log("Start");

// This loop blocks for about 3 seconds
const start = Date.now();
while (Date.now() - start &lt; 3000) {
  // doing nothing... but blocking everything!
}

console.log("End — 3 seconds later, nothing could happen");

// During those 3 seconds:
// ❌ Clicks don't register
// ❌ Animations freeze
// ❌ The page feels dead
</code></pre>
<blockquote>
<p><strong>The root problem</strong></p>
<p>JavaScript runs on a <strong>single thread</strong> — meaning it can only do one thing at a time. Blocking that thread blocks <em>everything</em>: clicks, animations, rendering. Async code solves this by offloading slow tasks to the browser and coming back for the result later.</p>
</blockquote>
<h3><strong>The solution: use async patterns</strong></h3>
<p>Whenever you have a slow operation, reach for async. Here are the three main tools JavaScript gives you:</p>
<pre><code class="language-javascript">// 1. Callbacks (oldest, gets messy quickly)
fetchData(function(result) {
  console.log(result);
});

// 2. Promises (cleaner)
fetchData()
  .then(result =&gt; console.log(result))
  .catch(error =&gt; console.log("Error!", error));

// 3. Async/Await (modern, most readable)
async function load() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.log("Error!", error);
  }
}
</code></pre>
<h3><strong>TL;DR — The Key Takeaways</strong></h3>
<p><strong>Synchronous:</strong> One task at a time, in order. Simple and predictable, but can freeze your app if a task takes too long.</p>
<p><strong>Asynchronous:</strong> Start a task, move on, come back when it's done. Keeps your app responsive and fast.</p>
<p><strong>Why it matters:</strong> JavaScript runs on a single thread. Blocking code kills the user experience. Async keeps everything running smoothly.</p>
<p><strong>Use async when...:</strong> You're fetching data, using timers, reading files, or doing anything that takes time. Use async/await for the cleanest code.</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript:
Try, Catch, Finally]]></title><description><![CDATA[Every developer, no matter how experienced, writes code that breaks. The question isn't if your code will encounter an error — it's what happens when it does. That's where error handling comes in.
In ]]></description><link>https://anilkambarweb.hashnode.dev/error-handling-in-javascript-try-catch-finally</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/error-handling-in-javascript-try-catch-finally</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[chai aur code]]></category><category><![CDATA[try-catch-finally]]></category><category><![CDATA[trycatch]]></category><category><![CDATA[WebDevCohort2026]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sat, 18 Apr 2026 05:31:02 GMT</pubDate><content:encoded><![CDATA[<p>Every developer, no matter how experienced, writes code that breaks. The question isn't <em>if</em> your code will encounter an error — it's <em>what happens when it does</em>. That's where error handling comes in.</p>
<p>In this guide, you'll learn how JavaScript lets you anticipate errors, respond to them, and keep your program running smoothly instead of crashing entirely.</p>
<h2><strong>What are errors in JavaScript?</strong></h2>
<p>An <strong>error</strong> is JavaScript's way of saying "something went wrong and I don't know how to continue." When an unhandled error occurs, your entire script stops running — like a power cut mid-sentence.</p>
<p>Here are the most common types you'll encounter as a beginner:</p>
<ul>
<li><p><strong>ReferenceError:</strong> Using a variable that doesn't exist yet.</p>
</li>
<li><p><strong>TypeError:</strong> Using a value in the wrong way (e.g., calling a non-function).</p>
</li>
<li><p><strong>SyntaxError:</strong> Writing code JavaScript can't parse or understand.</p>
</li>
<li><p><strong>RangeError:</strong> A number is outside an allowed range.</p>
</li>
</ul>
<pre><code class="language-javascript">// ReferenceError — 'price' was never declared
console.log(price);

// TypeError — null has no property 'toUpperCase'
let name = null;
name.toUpperCase();

// Both cause the script to STOP immediately!
</code></pre>
<blockquote>
<p><strong>⚠ heads up</strong></p>
<p>These are called <strong>runtime errors</strong> — they only appear when the code actually runs, not when you write it. That's why testing matters!</p>
</blockquote>
<h2><strong>Using try and catch blocks</strong></h2>
<p>The try...catch statement lets you <em>attempt</em> something risky and <em>handle</em> the problem if it fails — without crashing your whole program.</p>
<p>Think of it like this: <strong>try</strong> is you attempting to open a door, and <strong>catch</strong> is the plan you have if the door is locked.</p>
<pre><code class="language-javascript">try {
  // Code that might fail goes here
  let result = riskyOperation();
  console.log(result);

} catch (error) {
  // This runs only if something went wrong above
  console.log("Oops! Something went wrong:", error.message);
}
</code></pre>
<p><strong>A real-world example</strong></p>
<p>Imagine you're trying to parse data that a user typed in. If they typed something invalid, JSON.parse() will throw an error. Here's how to handle it gracefully:</p>
<pre><code class="language-javascript">function parseUserInput(input) {
  try {
    let data = JSON.parse(input);
    console.log("Parsed successfully!", data);

  } catch (error) {
    // Instead of crashing, show a friendly message
    console.log("That doesn't look like valid data. Try again!");
  }
}

parseUserInput('{"name": "Alice"}'); // ✅ Works fine
parseUserInput("not valid json!!");  // ✅ Caught gracefully
</code></pre>
<blockquote>
<p><strong>💡 tip</strong></p>
<p>The error object inside catch has two handy properties: error.message (what went wrong) and <a href="http://error.name">error.name</a> (the type of error). Use them in your logs!</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/3fbe78d5-edee-4f96-b0d8-9e84100ace86.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>The finally block</strong></h2>
<p>The finally block is your guarantee. Code inside it <strong>always runs</strong> — whether your try succeeded or your catch fired. It's perfect for cleanup tasks.</p>
<p>Common uses for finally: closing a loading spinner, releasing a file, or hiding a progress bar.</p>
<pre><code class="language-javascript">function fetchData() {
  showLoadingSpinner(); // Show spinner before we start

  try {
    let data = getDataFromServer();
    displayData(data);

  } catch (error) {
    showErrorMessage("Could not load data.");

  } finally {
    // This ALWAYS runs — success or failure!
    hideLoadingSpinner();
  }
}
</code></pre>
<blockquote>
<p><strong>ℹ info</strong></p>
<p>Think of finally as the responsible adult who tidies up no matter what happened at the party — whether it was great or a disaster.</p>
</blockquote>
<p><strong>in simple words</strong></p>
<p><strong>try  — "Let me attempt this"</strong></p>
<p>You write the code you <em>want</em> to run. JavaScript will try its best to execute it. Like placing a food order — you tell the waiter what you want.</p>
<p><strong>catch  — "If something breaks, do this instead"</strong></p>
<p>If the <strong>try</strong> code fails, <strong>catch</strong> takes over. Like the waiter saying "Sorry, that dish is unavailable — here's what we can offer instead." Your app stays alive.</p>
<p><strong>finally  — "Always do this, no matter what"</strong></p>
<p>Runs whether the order succeeded or failed. Like the restaurant always bringing your bill at the end — regardless of how the meal went.</p>
<h2><strong>Throwing custom errors</strong></h2>
<p>Sometimes JavaScript doesn't throw an error, but <em>you</em> want to because the data doesn't make sense. You can create and throw your own errors using the throw keyword.</p>
<pre><code class="language-javascript">function setAge(age) {
  if (age &lt; 0 || age &gt; 150) {
    // Throw our own custom error
    throw new Error("Age must be between 0 and 150!");
  }
  console.log("Age set to:", age);
}

try {
  setAge(-5);    // This triggers our custom throw
} catch (error) {
  console.log(error.message); // "Age must be between 0 and 150!"
}
</code></pre>
<p>You can also create <strong>custom error classes</strong> for more advanced scenarios — useful when building larger apps:</p>
<pre><code class="language-javascript">class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

try {
  throw new ValidationError("Email is not valid!");
} catch (error) {
  console.log(error.name);    // "ValidationError"
  console.log(error.message); // "Email is not valid!"
}
</code></pre>
<h2><strong>Why error handling matters</strong></h2>
<p>Skipping error handling is like building a car without airbags — fine until something goes wrong. Here's what good error handling does for you:</p>
<p><strong>graceful failure:</strong> Instead of a blank screen or frozen page, users see a helpful message. Your app stays alive.</p>
<p><strong>easier debugging:</strong> Log the error.message and error.stack to understand exactly what went wrong and where.</p>
<p><strong>user trust:</strong> Apps that handle errors well feel professional and reliable — even when things go sideways.</p>
<p><strong>recovery:</strong> You can retry failed operations, show fallback data, or redirect users instead of just giving up.</p>
<h3><strong>Quick recap</strong></h3>
<ul>
<li><p><strong>try</strong> — wrap risky code that might fail</p>
</li>
<li><p><strong>catch</strong> — handle the error when it happens</p>
</li>
<li><p><strong>finally</strong> — always runs, great for cleanup</p>
</li>
<li><p><strong>throw</strong> — create your own meaningful errors</p>
</li>
<li><p>Good error handling = better UX, easier debugging, more trust</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[If you've seen ... in JavaScript code and wondered what it does — you're not alone. Those three little dots are powerful, and depending on where you use them, they behave in two completely different w]]></description><link>https://anilkambarweb.hashnode.dev/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://anilkambarweb.hashnode.dev/spread-vs-rest-operators-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[restvsspread]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Dev 2026]]></category><dc:creator><![CDATA[Anil Kambar]]></dc:creator><pubDate>Sun, 12 Apr 2026 04:37:54 GMT</pubDate><content:encoded><![CDATA[<p>If you've seen <code>...</code> in JavaScript code and wondered what it does — you're not alone. Those three little dots are powerful, and depending on <em>where</em> you use them, they behave in two completely different ways: as the <strong>spread</strong> operator or the <strong>rest</strong> operator.</p>
<p>Let's break each one down with simple examples.</p>
<h2>The Spread Operator: Expanding Values</h2>
<p>Think of the spread operator like unpacking a suitcase. It takes an array or object and <em>spreads</em> its contents out individually.</p>
<p><strong>With arrays:</strong></p>
<pre><code class="language-javascript">const fruits = ["apple", "banana"];
const moreFruits = [...fruits, "cherry"];
// Result: ["apple", "banana", "cherry"]
</code></pre>
<p><strong>With objects:</strong></p>
<pre><code class="language-javascript">const user = { name: "Alice", age: 25 };
const updatedUser = { ...user, city: "Paris" };
// Result: { name: "Alice", age: 25, city: "Paris" }
</code></pre>
<p><strong>Here's how to picture it visually:</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/ed17c85a-02bf-4992-8816-99ed2b3c1167.png" alt="" style="display:block;margin:0 auto" />

<h2>The Rest Operator: Collecting Values</h2>
<p>The rest operator is the <em>opposite</em> — it collects multiple values and packs them into an array. You'll see it most often in function parameters.</p>
<p><strong>In a function:</strong></p>
<pre><code class="language-javascript">function addAll(...numbers) {
  return numbers.reduce((sum, n) =&gt; sum + n, 0);
}

addAll(1, 2, 3, 4); // numbers = [1, 2, 3, 4] → returns 10
</code></pre>
<p><strong>Collecting leftover items:</strong></p>
<pre><code class="language-javascript">const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first = 10, second = 20, rest = [30, 40, 50]
</code></pre>
<p><strong>Now let's see the rest operator visually:</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/69511cf4280f4c7f5f0e0c29/857a6e4e-6ea4-480e-80f5-652599412fce.png" alt="" style="display:block;margin:0 auto" />

<h2>Spread vs Rest: Key Differences at a Glance</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Spread <code>...</code></th>
<th>Rest <code>...</code></th>
</tr>
</thead>
<tbody><tr>
<td>What it does</td>
<td><strong>Expands</strong> values outward</td>
<td><strong>Collects</strong> values inward</td>
</tr>
<tr>
<td>Used in</td>
<td>Arrays, objects, function <em>calls</em></td>
<td>Function <em>definitions</em>, destructuring</td>
</tr>
<tr>
<td>Think of it as</td>
<td>Unpacking a box</td>
<td>Packing a bag</td>
</tr>
<tr>
<td>Result</td>
<td>Individual elements</td>
<td>A single array</td>
</tr>
</tbody></table>
<h2>Practical Use Cases</h2>
<h3><strong>1. Copying an array (spread)</strong></h3>
<pre><code class="language-javascript">const original = [1, 2, 3];
const copy = [...original]; // safe copy, not a reference
</code></pre>
<p>This is a common gotcha for beginners — without spread, <code>const copy = original</code> just points to the <em>same</em> array.</p>
<h3><strong>2. Merging two objects (spread)</strong></h3>
<pre><code class="language-javascript">const defaults = { theme: "light", lang: "en" };
const userSettings = { lang: "fr" };
const settings = { ...defaults, ...userSettings };
// Result: { theme: "light", lang: "fr" }
</code></pre>
<p><code>userSettings</code> overrides <code>defaults</code> where keys match.</p>
<h3><strong>3. Flexible function arguments (rest)</strong></h3>
<pre><code class="language-javascript">function greetAll(greeting, ...names) {
  names.forEach(name =&gt; console.log(`\({greeting}, \){name}!`));
}

greetAll("Hello", "Alice", "Bob", "Charlie");
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!
</code></pre>
<p><code>greeting</code> gets the first argument, and <code>...names</code> catches everything else.</p>
<h3><strong>4. Destructuring with rest</strong></h3>
<pre><code class="language-javascript">const scores = [98, 76, 55, 43, 30];
const [top, runner, ...others] = scores;
// top = 98, runner = 76, others = [55, 43, 30]
</code></pre>
<blockquote>
<p>💡 The Golden Rule<br />Same syntax (<code>...</code>), totally different purpose depending on context.  </p>
<p>Writing <code>...</code> <em>inside a function call or array literal</em> → <strong>spread</strong> (expanding)<br />Writing <code>...</code> <em>in a function parameter or destructuring</em> → <strong>rest</strong> (collecting)</p>
</blockquote>
]]></content:encoded></item></channel></rss>