<?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[new_cohort_blog_2026]]></title><description><![CDATA[new_cohort_blog_2026]]></description><link>https://newcohortblog2026.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 23 Jun 2026 16:35:35 GMT</lastBuildDate><atom:link href="https://newcohortblog2026.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[Problem Statement (Why do we need this?)
In JavaScript, we often work with objects and arrays.
But without a clean way to access values, our code becomes:

repetitive

long

hard to read


Example pro]]></description><link>https://newcohortblog2026.hashnode.dev/destructuring-in-javascript</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/destructuring-in-javascript</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Mon, 22 Jun 2026 14:55:46 GMT</pubDate><content:encoded><![CDATA[<h2>Problem Statement (Why do we need this?)</h2>
<p>In JavaScript, we often work with <strong>objects and arrays</strong>.</p>
<p>But without a clean way to access values, our code becomes:</p>
<ul>
<li><p>repetitive</p>
</li>
<li><p>long</p>
</li>
<li><p>hard to read</p>
</li>
</ul>
<h3>Example problem:</h3>
<pre><code class="language-plaintext">const user = {
  name: "Amit",
  age: 22,
  city: "Pune"
};

console.log(user.name);
console.log(user.age);
console.log(user.city);
</code></pre>
<p>Here we are repeating <code>user.</code> again and again.</p>
<p>Now imagine doing this in a big project with 50+ fields</p>
<p>This is where <strong>destructuring</strong> helps us.</p>
<h2>What is Destructuring?</h2>
<p><strong>Destructuring means extracting values from arrays or objects and storing them in variables in a simple way.</strong></p>
<p>Instead of writing:</p>
<pre><code class="language-plaintext">user.name
user.age
</code></pre>
<p>We directly get:</p>
<pre><code class="language-plaintext">name
age
</code></pre>
<h1>1. Array Destructuring</h1>
<h2>Before (Normal way)</h2>
<pre><code class="language-plaintext">const colors = ["red", "green", "blue"];

const first = colors[0];
const second = colors[1];
const third = colors[2];
</code></pre>
<p>Too much repetition</p>
<hr />
<h2>After (Destructuring)</h2>
<pre><code class="language-plaintext">const colors = ["red", "green", "blue"];

const [first, second, third] = colors;

console.log(first);  // red
console.log(second); // green
console.log(third);  // blue
</code></pre>
<h3>Mapping idea:</h3>
<pre><code class="language-plaintext">Array → Variables
[red, green, blue] → first, second, third
</code></pre>
<hr />
<h1>2. Object Destructuring</h1>
<h2>Before</h2>
<pre><code class="language-plaintext">const user = {
  name: "Amit",
  age: 22
};

const name = user.name;
const age = user.age;
</code></pre>
<hr />
<h2>After</h2>
<pre><code class="language-plaintext">const user = {
  name: "Amit",
  age: 22
};

const { name, age } = user;

console.log(name); // Amit
console.log(age);  // 22
</code></pre>
<h3>Mapping idea:</h3>
<pre><code class="language-plaintext">Object → Variables
{name: "Amit"} → name
</code></pre>
<h2>Renaming while destructuring</h2>
<pre><code class="language-plaintext">const user = {
  name: "Amit"
};

const { name: userName } = user;

console.log(userName); // Amit
</code></pre>
<p>Sometimes data is missing.</p>
<h2>Without default</h2>
<pre><code class="language-plaintext">const user = {};

const name = user.name;

console.log(name); // undefined
</code></pre>
<hr />
<h2>With default</h2>
<pre><code class="language-plaintext">const user = {};

const { name = "Guest" } = user;

console.log(name); // Guest
</code></pre>
<h2>Array default value</h2>
<pre><code class="language-plaintext">const colors = [];

const [first = "red"] = colors;

console.log(first); // red
</code></pre>
<h1>Benefits of Destructuring</h1>
<h3>1. Less code</h3>
<pre><code class="language-plaintext">const { name, age } = user;
</code></pre>
<p>Instead of:</p>
<pre><code class="language-plaintext">const name = user.name;
const age = user.age;
</code></pre>
<h3>2. More readable</h3>
<p>Code becomes clean and easy to understand.</p>
<h3>3. Avoid repetition</h3>
<p>No need to write <code>user.user.user...</code></p>
]]></content:encoded></item><item><title><![CDATA[What is Middleware in Express and How It Works]]></title><description><![CDATA[The Problem: Why Do We Need Middleware?
Imagine you are entering an airport.
Before boarding a plane, you pass through several checkpoints:

Security Check

Identity Verification

Baggage Check

Board]]></description><link>https://newcohortblog2026.hashnode.dev/what-is-middleware-in-express-and-how-it-works</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/what-is-middleware-in-express-and-how-it-works</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Sun, 21 Jun 2026 07:53:52 GMT</pubDate><content:encoded><![CDATA[<h2>The Problem: Why Do We Need Middleware?</h2>
<p>Imagine you are entering an airport.</p>
<p>Before boarding a plane, you pass through several checkpoints:</p>
<ol>
<li><p>Security Check</p>
</li>
<li><p>Identity Verification</p>
</li>
<li><p>Baggage Check</p>
</li>
<li><p>Boarding Gate</p>
</li>
</ol>
<p>Only after passing these checkpoints can you enter the airplane.</p>
<p>Express applications work in a very similar way.</p>
<p>When a client sends a request to a server, we often need to:</p>
<ul>
<li><p>Log the request</p>
</li>
<li><p>Check if the user is authenticated</p>
</li>
<li><p>Validate request data</p>
</li>
<li><p>Parse JSON data</p>
</li>
</ul>
<p>If we write this code inside every route, our application becomes repetitive and difficult to maintain.</p>
<p>This is the problem Middleware solves.</p>
<h1>What is Middleware?</h1>
<p>Middleware is a function that runs between receiving a request and sending a response.</p>
<p>Think of middleware as a checkpoint.</p>
<pre><code class="language-plaintext">Client Request
      |
      v
  Middleware
      |
      v
 Route Handler
      |
      v
Server Response
</code></pre>
<p>Middleware can:</p>
<ul>
<li><p>Read request data</p>
</li>
<li><p>Modify request data</p>
</li>
<li><p>Stop the request</p>
</li>
<li><p>Send a response</p>
</li>
<li><p>Pass control to the next middleware</p>
</li>
</ul>
<h1>Express Request Lifecycle</h1>
<p>When a request reaches the server, it follows a pipeline.</p>
<pre><code class="language-plaintext">Request
   |
   v
Middleware 1
   |
   v
Middleware 2
   |
   v
Middleware 3
   |
   v
Route Handler
   |
   v
Response
</code></pre>
<p>Every middleware gets a chance to process the request before it reaches the route handler.</p>
<h1>Middleware Syntax</h1>
<p>A middleware function receives three parameters:</p>
<pre><code class="language-plaintext">function middleware(req, res, next) {
  console.log("Middleware executed");
  next();
}
</code></pre>
<p>Parameters:</p>
<ul>
<li><p><code>req</code> → Request object</p>
</li>
<li><p><code>res</code> → Response object</p>
</li>
<li><p><code>next</code> → Function that passes control to the next middleware</p>
</li>
</ul>
<h1>Understanding next()</h1>
<p>The <code>next()</code> function is one of the most important parts of middleware.</p>
<p>Without <code>next()</code>, the request gets stuck.</p>
<p>Example:</p>
<pre><code class="language-plaintext">app.use((req, res, next) =&gt; {
  console.log("First Middleware");
  next();
});

app.get("/", (req, res) =&gt; {
  res.send("Home Page");
});
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">First Middleware
Home Page
</code></pre>
<p>Flow:</p>
<pre><code class="language-plaintext">Request
   |
Middleware
   |
 next()
   |
Route Handler
   |
Response
</code></pre>
<h1>What Happens Without next()?</h1>
<pre><code class="language-plaintext">app.use((req, res, next) =&gt; {
  console.log("Middleware Running");
});
</code></pre>
<p>Now the request never reaches the route handler.</p>
<pre><code class="language-plaintext">Request
   |
Middleware
   |
STOP
</code></pre>
<p>The browser keeps waiting because Express does not know what to do next.</p>
<h1>Types of Middleware in Express</h1>
<p>Express provides different types of middleware.</p>
<h1>1. Application-Level Middleware</h1>
<p>This middleware is attached to the entire application.</p>
<p>Example:</p>
<pre><code class="language-plaintext">app.use((req, res, next) =&gt; {
  console.log("Application Middleware");
  next();
});
</code></pre>
<p>This middleware runs for every request.</p>
<pre><code class="language-plaintext">/login
/signup
/products
/profile
</code></pre>
<p>All routes pass through it.</p>
<h1>2. Router-Level Middleware</h1>
<p>Sometimes we want middleware for only specific routes.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const router = express.Router();

router.use((req, res, next) =&gt; {
  console.log("Router Middleware");
  next();
});

router.get("/profile", (req, res) =&gt; {
  res.send("Profile Page");
});
</code></pre>
<p>Only routes inside that router use this middleware.</p>
<h1>3. Built-in Middleware</h1>
<p>Express provides some middleware out of the box.</p>
<h2>express.json()</h2>
<p>Converts JSON request data into JavaScript objects.</p>
<pre><code class="language-plaintext">app.use(express.json());
</code></pre>
<p>Example Request:</p>
<pre><code class="language-plaintext">{
  "name": "Ashish"
}
</code></pre>
<p>Now you can access:</p>
<pre><code class="language-plaintext">req.body.name
</code></pre>
<p>Without <code>express.json()</code>, <code>req.body</code> would be undefined.</p>
<h2>express.static()</h2>
<p>Used to serve static files.</p>
<pre><code class="language-plaintext">app.use(express.static("public"));
</code></pre>
<p>Files inside the public folder become accessible directly.</p>
<p>Example:</p>
<pre><code class="language-plaintext">public/logo.png
</code></pre>
<p>Access:</p>
<pre><code class="language-plaintext">http://localhost:3000/logo.png
</code></pre>
<h1>Middleware Execution Order</h1>
<p>Middleware executes in the order it is registered.</p>
<p>Example:</p>
<pre><code class="language-plaintext">app.use((req, res, next) =&gt; {
  console.log("Middleware 1");
  next();
});

app.use((req, res, next) =&gt; {
  console.log("Middleware 2");
  next();
});

app.get("/", (req, res) =&gt; {
  console.log("Route Handler");
  res.send("Hello");
});
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Middleware 1
Middleware 2
Route Handler
</code></pre>
<p>Flow:</p>
<pre><code class="language-plaintext">Request
   |
Middleware 1
   |
Middleware 2
   |
Route Handler
   |
Response
</code></pre>
<h1>Real World Example 1: Logging Middleware</h1>
<p>Suppose we want to know which routes users are accessing.</p>
<pre><code class="language-plaintext">app.use((req, res, next) =&gt; {
  console.log(`\({req.method} \){req.url}`);
  next();
});
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">GET /products
POST /login
GET /profile
</code></pre>
<p>This is called Logging Middleware.</p>
<h1>Real World Example 2: Authentication Middleware</h1>
<p>Suppose some routes require login.</p>
<pre><code class="language-plaintext">function authMiddleware(req, res, next) {
  const isLoggedIn = true;

  if (!isLoggedIn) {
    return res.status(401).send("Unauthorized");
  }

  next();
}
</code></pre>
<p>Using it:</p>
<pre><code class="language-plaintext">app.get("/profile", authMiddleware, (req, res) =&gt; {
  res.send("Welcome User");
});
</code></pre>
<p>Flow:</p>
<pre><code class="language-plaintext">Request
   |
Authentication Check
   |
   +--&gt; Not Logged In
   |        |
   |    Unauthorized
   |
   +--&gt; Logged In
            |
        Route Handler
</code></pre>
<h1>Real World Example 3: Request Validation</h1>
<p>Before creating a user, we can validate data.</p>
<pre><code class="language-plaintext">function validateUser(req, res, next) {
  if (!req.body.name) {
    return res.status(400).send("Name Required");
  }

  next();
}
</code></pre>
<p>Using it:</p>
<pre><code class="language-plaintext">app.post("/users", validateUser, (req, res) =&gt; {
  res.send("User Created");
});
</code></pre>
<p>This ensures invalid data never reaches the route handler.</p>
<h1>Middleware Chain Example</h1>
<p>Multiple middleware can work together.</p>
<pre><code class="language-plaintext">app.get(
  "/profile",
  logger,
  authMiddleware,
  validateUser,
  (req, res) =&gt; {
    res.send("Profile Data");
  }
);
</code></pre>
<p>Execution Order:</p>
<pre><code class="language-plaintext">Request
   |
Logger
   |
Authentication
   |
Validation
   |
Route Handler
   |
Response
</code></pre>
<p>This is called a Middleware Chain.</p>
<h1>Why Middleware is Useful</h1>
<p>Without middleware:</p>
<pre><code class="language-plaintext">app.get("/profile", () =&gt; {
  // logging code
  // auth code
  // validation code
  // route logic
});
</code></pre>
<p>Every route would contain repeated code.</p>
<p>With middleware:</p>
<pre><code class="language-plaintext">app.get(
  "/profile",
  logger,
  authMiddleware,
  validateUser,
  handler
);
</code></pre>
<p>The code becomes:</p>
<ul>
<li><p>Cleaner</p>
</li>
<li><p>Reusable</p>
</li>
<li><p>Easier to maintain</p>
</li>
<li><p>Easier to debug</p>
</li>
</ul>
<h1>Conclusion</h1>
<p>Middleware is one of the most powerful features of Express.</p>
<p>Think of it as a checkpoint in the request pipeline.</p>
<p>Whenever a request arrives, middleware gets an opportunity to inspect, modify, validate, or even stop the request before it reaches the route handler.</p>
<p>By separating logging, authentication, validation, and other common tasks into middleware, Express applications become cleaner, more organized, and easier to maintain.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Promises Explained for Beginners]]></title><description><![CDATA[The Problem: Why Do We Need Promises?
Imagine you order a pizza.
You place the order and the pizza shop says:

"Your pizza will be delivered in 30 minutes."

Now you don't stand outside the shop waiti]]></description><link>https://newcohortblog2026.hashnode.dev/javascript-promises-explained-for-beginners</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/javascript-promises-explained-for-beginners</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Sun, 21 Jun 2026 07:43:25 GMT</pubDate><content:encoded><![CDATA[<h2>The Problem: Why Do We Need Promises?</h2>
<p>Imagine you order a pizza.</p>
<p>You place the order and the pizza shop says:</p>
<blockquote>
<p>"Your pizza will be delivered in 30 minutes."</p>
</blockquote>
<p>Now you don't stand outside the shop waiting for 30 minutes. You continue doing other work and receive the pizza when it's ready.</p>
<p>Computers face a similar situation.</p>
<p>Sometimes JavaScript needs to wait for things like:</p>
<ul>
<li><p>API requests</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>Reading files</p>
</li>
<li><p>Timers</p>
</li>
</ul>
<p>These tasks take time.</p>
<p>If JavaScript stopped everything and waited, the application would become slow and unresponsive.</p>
<p>So JavaScript starts the task and continues doing other work.</p>
<p>The question is:</p>
<p><strong>How will JavaScript know when the result is ready?</strong></p>
<p>That's where Promises come in.</p>
<h1>What is a Promise?</h1>
<p>A Promise is an object that represents a value that will be available in the future.</p>
<p>Think of it as:</p>
<blockquote>
<p>"I don't have the result right now, but I promise I'll give it to you later."</p>
</blockquote>
<p>Example:</p>
<pre><code class="language-plaintext">const promise = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; {
    resolve("Pizza Delivered!");
  }, 3000);
});
</code></pre>
<p>In this example:</p>
<ul>
<li><p>Pizza is not available immediately.</p>
</li>
<li><p>After 3 seconds, it gets delivered.</p>
</li>
<li><p>The Promise notifies us when the result is ready.</p>
</li>
</ul>
<h1>Promise States</h1>
<p>Every Promise can be in one of three states.</p>
<h2>1. Pending</h2>
<p>The task is still running.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const promise = new Promise(() =&gt; {});
</code></pre>
<p>Current state:</p>
<pre><code class="language-plaintext">Pending
</code></pre>
<p>The result is not ready yet.</p>
<h2>2. Fulfilled</h2>
<p>The task completed successfully.</p>
<pre><code class="language-plaintext">resolve("Success");
</code></pre>
<p>State:</p>
<pre><code class="language-plaintext">Fulfilled
</code></pre>
<p>Result is available.</p>
<h2>3. Rejected</h2>
<p>Something went wrong.</p>
<pre><code class="language-plaintext">reject("Error");
</code></pre>
<p>State:</p>
<pre><code class="language-plaintext">Rejected
</code></pre>
<p>An error occurred.</p>
<h1>Promise Lifecycle</h1>
<p>A Promise always follows this path:</p>
<pre><code class="language-plaintext">          Promise Created
                 |
                 v
             Pending
             /     \
            /       \
           v         v
      Fulfilled   Rejected
</code></pre>
<p>A Promise starts in the Pending state and eventually becomes either Fulfilled or Rejected.</p>
<p>It cannot go back to Pending.</p>
<h1>Creating a Promise</h1>
<p>Example:</p>
<pre><code class="language-plaintext">const pizzaPromise = new Promise((resolve, reject) =&gt; {
  const pizzaReady = true;

  if (pizzaReady) {
    resolve("Pizza Delivered");
  } else {
    reject("Pizza Cancelled");
  }
});
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>resolve()</code> means success.</p>
</li>
<li><p><code>reject()</code> means failure.</p>
</li>
</ul>
<h1>Handling Success and Failure</h1>
<p>We use <code>.then()</code> and <code>.catch()</code>.</p>
<pre><code class="language-plaintext">pizzaPromise
  .then((result) =&gt; {
    console.log(result);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Pizza Delivered
</code></pre>
<p>If something goes wrong:</p>
<pre><code class="language-plaintext">Pizza Cancelled
</code></pre>
<h1>Understanding .then()</h1>
<p><code>.then()</code> runs when the Promise is fulfilled.</p>
<pre><code class="language-plaintext">promise.then((result) =&gt; {
  console.log(result);
});
</code></pre>
<p>Think of it as:</p>
<blockquote>
<p>"When the task finishes successfully, run this code."</p>
</blockquote>
<h1>Understanding .catch()</h1>
<p><code>.catch()</code> runs when the Promise is rejected.</p>
<pre><code class="language-plaintext">promise.catch((error) =&gt; {
  console.log(error);
});
</code></pre>
<p>Think of it as:</p>
<blockquote>
<p>"If something fails, run this code."</p>
</blockquote>
<h1>Promises as Future Values</h1>
<p>Let's imagine a friend says:</p>
<blockquote>
<p>"I'll send you the notes tomorrow."</p>
</blockquote>
<p>Right now you don't have the notes.</p>
<p>But you have a promise that you'll receive them later.</p>
<p>Similarly:</p>
<pre><code class="language-plaintext">const notesPromise = getNotes();
</code></pre>
<p>At this moment:</p>
<pre><code class="language-plaintext">notesPromise
</code></pre>
<p>does not contain the notes.</p>
<p>It contains a Promise that will provide the notes in the future.</p>
<h1>Callback Approach</h1>
<p>Before Promises, developers often used callbacks.</p>
<p>Example:</p>
<pre><code class="language-plaintext">getUser(function(user) {
  getPosts(user.id, function(posts) {
    getComments(posts[0].id, function(comments) {
      console.log(comments);
    });
  });
});
</code></pre>
<p>Notice how code keeps moving to the right.</p>
<p>This is called:</p>
<pre><code class="language-plaintext">Callback Hell
</code></pre>
<p>or</p>
<pre><code class="language-plaintext">Pyramid of Doom
</code></pre>
<p>Because the code becomes difficult to read and maintain.</p>
<h1>Promise Version</h1>
<p>The same code can be written using Promises.</p>
<pre><code class="language-plaintext">getUser()
  .then((user) =&gt; {
    return getPosts(user.id);
  })
  .then((posts) =&gt; {
    return getComments(posts[0].id);
  })
  .then((comments) =&gt; {
    console.log(comments);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>This looks much cleaner and easier to understand.</p>
<h1>Promise Chaining</h1>
<p>A Promise can return another Promise.</p>
<p>This allows multiple asynchronous operations to run in sequence.</p>
<p>Example:</p>
<pre><code class="language-plaintext">getUser()
  .then((user) =&gt; {
    return getPosts(user.id);
  })
  .then((posts) =&gt; {
    return getComments(posts[0].id);
  })
  .then((comments) =&gt; {
    console.log(comments);
  });
</code></pre>
<p>Each <code>.then()</code> waits for the previous Promise to finish.</p>
<p>This is called:</p>
<pre><code class="language-plaintext">Promise Chaining
</code></pre>
<h1>Real World Example</h1>
<p>Fetching data from an API:</p>
<pre><code class="language-plaintext">fetch("https://jsonplaceholder.typicode.com/users")
  .then((response) =&gt; response.json())
  .then((data) =&gt; {
    console.log(data);
  })
  .catch((error) =&gt; {
    console.log(error);
  });
</code></pre>
<p>Flow:</p>
<pre><code class="language-plaintext">Send Request
      |
      v
   Pending
      |
      v
 Receive Response
      |
      v
 Fulfilled
</code></pre>
<p>If the network fails:</p>
<pre><code class="language-plaintext">Rejected
</code></pre>
<h1>Callback vs Promise</h1>
<table>
<thead>
<tr>
<th>Callback</th>
<th>Promise</th>
</tr>
</thead>
<tbody><tr>
<td>Can lead to callback hell</td>
<td>Cleaner code</td>
</tr>
<tr>
<td>Hard to manage errors</td>
<td>Easy error handling</td>
</tr>
<tr>
<td>Difficult to read</td>
<td>More readable</td>
</tr>
<tr>
<td>Nested structure</td>
<td>Chaining structure</td>
</tr>
</tbody></table>
<h1>Conclusion</h1>
<p>Promises help JavaScript handle tasks that take time, such as API calls, database operations, file reading, and timers.</p>
<p>Instead of deeply nested callbacks, Promises provide a cleaner and more readable way to manage asynchronous code.</p>
<p>Think of a Promise as a future value:</p>
<blockquote>
<p>"The result is not available right now, but it will be available later."</p>
</blockquote>
<p>Once you understand Promises, learning <code>async/await</code> becomes much easier because <code>async/await</code> is built on top of Promises.</p>
]]></content:encoded></item><item><title><![CDATA[Handling File Uploads in Express with Multer]]></title><description><![CDATA[The Problem: Why file upload is difficult
When users upload things on a website like:

photos 📸

PDFs 📄

images 🖼️


It does not come like normal text.
Normal data looks like:
{ "name": "Amit" }

B]]></description><link>https://newcohortblog2026.hashnode.dev/handling-file-uploads-in-express-with-multer</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/handling-file-uploads-in-express-with-multer</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Sat, 20 Jun 2026 08:13:07 GMT</pubDate><content:encoded><![CDATA[<h2>The Problem: Why file upload is difficult</h2>
<p>When users upload things on a website like:</p>
<ul>
<li><p>photos 📸</p>
</li>
<li><p>PDFs 📄</p>
</li>
<li><p>images 🖼️</p>
</li>
</ul>
<p>It does not come like normal text.</p>
<p>Normal data looks like:</p>
<pre><code class="language-plaintext">{ "name": "Amit" }
</code></pre>
<p>But files are different:</p>
<ul>
<li><p>they are big</p>
</li>
<li><p>they are not simple text</p>
</li>
<li><p>they come in a special format</p>
</li>
</ul>
<p>Express cannot understand files directly.</p>
<h2>Simple Problem</h2>
<p>Express can handle text data easily<br />But it cannot handle files by itself</p>
<p>So we need help.</p>
<h2>Solution: We need a helper (Middleware)</h2>
<p>Middleware is something that works between:</p>
<ul>
<li><p>user request</p>
</li>
<li><p>server response</p>
</li>
</ul>
<p>It helps Express understand special data like files.</p>
<h2>What is Multer?</h2>
<p>Multer is a tool used in Express to handle file uploads.</p>
<h3>Simple meaning:</h3>
<p>Multer = a helper that handles files</p>
<p>It does 3 things:</p>
<ul>
<li><p>takes file from request</p>
</li>
<li><p>saves file in a folder</p>
</li>
<li><p>gives file info to your code</p>
</li>
</ul>
<h2>How file upload works (simple flow)</h2>
<h3>Step 1:</h3>
<p>User selects a file 📸</p>
<h3>Step 2:</h3>
<p>Browser sends file to server</p>
<h3>Step 3:</h3>
<p>Multer receives the file</p>
<h3>Step 4:</h3>
<p>Multer saves file in a folder</p>
<h3>Step 5:</h3>
<p>Your server gets file details</p>
<pre><code class="language-plaintext">req.file
</code></pre>
<h2>Basic setup</h2>
<h3>1. Install Multer</h3>
<pre><code class="language-plaintext">npm install multer
</code></pre>
<h3>2. Set storage (where files will go)</h3>
<pre><code class="language-plaintext">import multer from "multer";

const storage = multer.diskStorage({
  destination: (req, file, cb) =&gt; {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) =&gt; {
    cb(null, Date.now() + "-" + file.originalname);
  },
});
</code></pre>
<p>Meaning:</p>
<ul>
<li><p>files will be saved in <code>uploads/</code> folder</p>
</li>
<li><p>each file will have a unique name</p>
</li>
</ul>
<h3>3. Create upload middleware</h3>
<pre><code class="language-plaintext">const upload = multer({ storage });
</code></pre>
<h2>Single file upload</h2>
<pre><code class="language-plaintext">app.post("/upload", upload.single("photo"), (req, res) =&gt; {
  console.log(req.file);
  res.send("File uploaded successfully");
});
</code></pre>
<p>Meaning:</p>
<ul>
<li><p>only one file is uploaded</p>
</li>
<li><p>file data is in <code>req.file</code></p>
</li>
</ul>
<h2>Multiple file upload</h2>
<pre><code class="language-plaintext">app.post("/upload", upload.array("photos", 5), (req, res) =&gt; {
  console.log(req.files);
  res.send("Multiple files uploaded successfully");
});
</code></pre>
<p>Meaning:</p>
<ul>
<li><p>multiple files allowed</p>
</li>
<li><p>maximum 5 files</p>
</li>
<li><p>file data is in <code>req.files</code></p>
</li>
</ul>
<h2>Show uploaded files in browser</h2>
<pre><code class="language-plaintext">app.use("/uploads", express.static("uploads"));
</code></pre>
<p>Now files can be opened like:</p>
<pre><code class="language-plaintext">http://localhost:3000/uploads/image.jpg
</code></pre>
<h2>Full flow</h2>
<pre><code class="language-plaintext">User selects file
      ↓
Browser sends file
      ↓
Server receives request
      ↓
Multer handles file
      ↓
File is saved in uploads folder
      ↓
Server gets file info (req.file)
      ↓
Response is sent
</code></pre>
]]></content:encoded></item><item><title><![CDATA[What is Node.js? JavaScript on the Server Explained]]></title><description><![CDATA[Most developers start their journey with JavaScript in the browser. But at some point, a question comes up:
“Can JavaScript run outside the browser?”
The answer changed everything in web development —]]></description><link>https://newcohortblog2026.hashnode.dev/what-is-node-js-javascript-on-the-server-explained</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/what-is-node-js-javascript-on-the-server-explained</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Thu, 18 Jun 2026 08:08:35 GMT</pubDate><content:encoded><![CDATA[<p>Most developers start their journey with JavaScript in the browser. But at some point, a question comes up:</p>
<p><strong>“Can JavaScript run outside the browser?”</strong></p>
<p>The answer changed everything in web development — <strong>Node.js</strong></p>
<h2>1. The Problem: JavaScript was only a browser language</h2>
<p>Originally, JavaScript was designed only to run inside browsers like Chrome or Firefox.</p>
<p>So it could:</p>
<ul>
<li><p>Handle button clicks</p>
</li>
<li><p>Validate forms</p>
</li>
<li><p>Update UI dynamically</p>
</li>
</ul>
<p>But it <strong>could NOT</strong>:</p>
<ul>
<li><p>Access databases</p>
</li>
<li><p>Handle file systems</p>
</li>
<li><p>Run backend APIs</p>
</li>
<li><p>Work like Java, PHP, or Python on servers</p>
</li>
</ul>
<p>In short:<br />JavaScript = frontend only language</p>
<p>Backend required separate languages like:</p>
<ul>
<li><p>Java</p>
</li>
<li><p>PHP</p>
</li>
<li><p>Python</p>
</li>
<li><p>Ruby</p>
</li>
</ul>
<p>This created a problem:</p>
<blockquote>
<p>Developers had to learn TWO different languages for frontend and backend.</p>
</blockquote>
<h2>2. The Big Idea: What if JavaScript could run on servers?</h2>
<p>This is where Node.js came in.</p>
<p>Node.js allows JavaScript to run outside the browser — especially on servers.</p>
<p>So now:</p>
<ul>
<li><p>Same language (JavaScript)</p>
</li>
<li><p>Same syntax</p>
</li>
<li><p>Same developer mindset</p>
</li>
</ul>
<p>One language for full-stack development</p>
<h2>3. How Node.js made it possible</h2>
<p>Node.js is not a programming language.</p>
<p>It is a <strong>runtime environment</strong>.</p>
<p>Think of it like this:</p>
<ul>
<li><p>JavaScript = instructions (language)</p>
</li>
<li><p>Node.js = machine that executes those instructions on server</p>
</li>
</ul>
<p>It is built on:</p>
<p>V8 (JavaScript engine)</p>
<h3>What is V8 (high level)?</h3>
<ul>
<li><p>It is the engine inside Google Chrome</p>
</li>
<li><p>It converts JavaScript into fast machine code</p>
</li>
<li><p>Node.js takes this engine outside the browser</p>
</li>
</ul>
<p>So basically:</p>
<blockquote>
<p>Node.js = V8 engine + extra server features</p>
</blockquote>
<h2>4. Event-driven architecture (core idea)</h2>
<p>Node.js uses something called <strong>event-driven, non-blocking I/O</strong></p>
<p>Simple meaning:</p>
<p>Instead of waiting for one task to finish, Node.js:</p>
<ul>
<li><p>Starts a task</p>
</li>
<li><p>Moves to next task</p>
</li>
<li><p>Comes back when first task is done</p>
</li>
</ul>
<h3>Example:</h3>
<p>If 3 users request data:</p>
<ul>
<li><p>Traditional backend → handles one by one (waiting)</p>
</li>
<li><p>Node.js → handles all together efficiently</p>
</li>
</ul>
<p>This makes Node.js very fast for scalable apps</p>
<h2>5. Browser JS vs Node.js (simple comparison)</h2>
<h3>Browser JavaScript</h3>
<ul>
<li><p>Runs in browser</p>
</li>
<li><p>Controls UI</p>
</li>
<li><p>Talks to DOM (buttons, pages)</p>
</li>
<li><p>Cannot access file system</p>
</li>
</ul>
<h3>Node.js JavaScript</h3>
<ul>
<li><p>Runs on server</p>
</li>
<li><p>Handles APIs</p>
</li>
<li><p>Talks to database</p>
</li>
<li><p>Can read/write files</p>
</li>
<li><p>Builds backend systems</p>
</li>
</ul>
<h2>6. Real-world use cases of Node.js</h2>
<p>Node.js is used in many production systems:</p>
<ul>
<li><p>API servers (REST / GraphQL)</p>
</li>
<li><p>Chat applications (real-time apps)</p>
</li>
<li><p>Streaming platforms</p>
</li>
<li><p>Backend for web apps</p>
</li>
<li><p>Microservices architecture</p>
</li>
<li><p>Tools like build systems (Webpack, Vite)</p>
</li>
</ul>
<p>Companies using Node.js:</p>
<ul>
<li><p>Netflix</p>
</li>
<li><p>PayPal</p>
</li>
<li><p>LinkedIn</p>
</li>
<li><p>Uber</p>
</li>
</ul>
<h2>7. Node.js vs Traditional Backend (Java / PHP)</h2>
<h3>Java / PHP approach:</h3>
<ul>
<li><p>Separate frontend + backend languages</p>
</li>
<li><p>More server overhead</p>
</li>
<li><p>Thread-based handling (heavy in some cases)</p>
</li>
</ul>
<h3>Node.js approach:</h3>
<ul>
<li><p>Single language (JavaScript everywhere)</p>
</li>
<li><p>Lightweight and fast</p>
</li>
<li><p>Event-driven model</p>
</li>
<li><p>Great for real-time apps</p>
</li>
</ul>
<p>That’s why startups love Node.js</p>
<h2>8. JavaScript vs Runtime (important interview point)</h2>
<p>This is a common confusion:</p>
<h3>JavaScript</h3>
<ul>
<li>A programming language</li>
</ul>
<h3>Node.js</h3>
<ul>
<li>A runtime environment that executes JavaScript outside the browser</li>
</ul>
<p>Same language, different environment</p>
]]></content:encoded></item><item><title><![CDATA[JWT Authentication in Node.js Explained Simply]]></title><description><![CDATA[JWT Authentication in Node.js: A Beginner-Friendly Guide
Imagine you're using Instagram, Facebook, or Amazon.
When you log in once, you can continue using the application without entering your passwor]]></description><link>https://newcohortblog2026.hashnode.dev/jwt-authentication-in-node-js-explained-simply</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/jwt-authentication-in-node-js-explained-simply</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Wed, 17 Jun 2026 03:38:21 GMT</pubDate><content:encoded><![CDATA[<h2>JWT Authentication in Node.js: A Beginner-Friendly Guide</h2>
<p>Imagine you're using Instagram, Facebook, or Amazon.</p>
<p>When you log in once, you can continue using the application without entering your password on every page.</p>
<p>Have you ever wondered how the application remembers that you are already logged in?</p>
<p>This is where <strong>authentication</strong> and <strong>JWT (JSON Web Token)</strong> come into the picture.</p>
<p>In this article, we'll understand JWT Authentication in Node.js in the simplest way possible.</p>
<h1>Why Authentication is Required</h1>
<h2>The Problem</h2>
<p>Suppose you have built a blogging application.</p>
<p>Anyone can access your website and try to:</p>
<ul>
<li><p>Create blog posts</p>
</li>
<li><p>Edit posts</p>
</li>
<li><p>Delete posts</p>
</li>
<li><p>View private information</p>
</li>
</ul>
<p>How will the server know who is a valid user?</p>
<p>Without authentication, anyone could perform actions they shouldn't.</p>
<h2>The Solution</h2>
<p>Authentication helps the server answer one important question:</p>
<blockquote>
<p>"Who is making this request?"</p>
</blockquote>
<p>When users prove their identity (usually with email and password), the server allows access to protected resources.</p>
<h1>What is Authentication?</h1>
<p>Authentication is the process of verifying a user's identity.</p>
<p>For example:</p>
<ol>
<li><p>User enters email and password.</p>
</li>
<li><p>Server checks the credentials.</p>
</li>
<li><p>If correct, the user is authenticated.</p>
</li>
<li><p>The user gets access to protected features.</p>
</li>
</ol>
<p>Think of authentication like showing your ID card before entering a secured office.</p>
<h1>What is JWT?</h1>
<p>JWT stands for <strong>JSON Web Token</strong>.</p>
<p>It is a compact string used to securely transfer user information between the client and server.</p>
<p>After a successful login, the server generates a JWT and sends it to the client.</p>
<p>The client stores the token and sends it with future requests.</p>
<p>Instead of asking for username and password every time, the server simply verifies the token.</p>
<h1>Why JWT Became Popular</h1>
<p>Before JWT, many applications stored login sessions on the server.</p>
<p>This created extra memory usage and complexity.</p>
<p>JWT introduced a simpler approach called <strong>Stateless Authentication</strong>.</p>
<h1>What is Stateless Authentication?</h1>
<h2>The Problem</h2>
<p>Imagine 10,000 users are logged in.</p>
<p>If the server stores login information for every user, memory usage keeps increasing.</p>
<p>Managing sessions becomes difficult.</p>
<h2>The Solution</h2>
<p>With JWT:</p>
<ul>
<li><p>The server creates a token.</p>
</li>
<li><p>The client stores the token.</p>
</li>
<li><p>The client sends the token with every request.</p>
</li>
<li><p>The server verifies the token.</p>
</li>
</ul>
<p>The server doesn't need to remember who is logged in.</p>
<p>This is called <strong>stateless authentication</strong>.</p>
<h1>Structure of a JWT</h1>
<p>A JWT contains three parts:</p>
<pre><code class="language-plaintext">HEADER.PAYLOAD.SIGNATURE
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJ1c2VySWQiOjEyMywiZW1haWwiOiJ1c2VyQGdtYWlsLmNvbSJ9
.
abcxyz123signature
</code></pre>
<p>Let's understand each section</p>
<h1>1. Header</h1>
<p>The header contains metadata about the token.</p>
<p>Example:</p>
<pre><code class="language-plaintext">{
  "alg": "HS256",
  "typ": "JWT"
}
</code></pre>
<p>It tells:</p>
<ul>
<li><p>Which algorithm is used</p>
</li>
<li><p>That the token type is JWT</p>
</li>
</ul>
<h1>2. Payload</h1>
<p>The payload contains user information.</p>
<p>Example:</p>
<pre><code class="language-plaintext">{
  "userId": 123,
  "email": "user@gmail.com"
}
</code></pre>
<p>This data is called <strong>claims</strong>.</p>
<p>Common claims include:</p>
<ul>
<li><p>User ID</p>
</li>
<li><p>Email</p>
</li>
<li><p>Role</p>
</li>
<li><p>Expiration time</p>
</li>
</ul>
<p>Important:</p>
<p>Do not store sensitive information like passwords inside the payload.</p>
<h1>3. Signature</h1>
<p>The signature ensures that the token has not been modified.</p>
<p>The server creates the signature using:</p>
<ul>
<li><p>Header</p>
</li>
<li><p>Payload</p>
</li>
<li><p>Secret Key</p>
</li>
</ul>
<p>When a request arrives, the server verifies the signature.</p>
<p>If someone changes the payload, verification fails.</p>
<h1>JWT Login Flow</h1>
<p>Let's understand the complete flow.</p>
<p>Step 1: User Logs In</p>
<p>The user sends:</p>
<pre><code class="language-plaintext">{
  "email": "user@gmail.com",
  "password": "123456"
}
</code></pre>
<h2>Step 2: Server Verifies Credentials</h2>
<p>The server checks the database.</p>
<p>If credentials are valid:</p>
<pre><code class="language-plaintext">const token = jwt.sign(
  { userId: user.id },
  process.env.JWT_SECRET,
  { expiresIn: "1h" }
);
</code></pre>
<h2>Step 3: Server Sends JWT</h2>
<p>Response:</p>
<pre><code class="language-plaintext">{
  "token": "jwt_token_here"
}
</code></pre>
<h2>Step 4: Client Stores Token</h2>
<p>The client stores the token:</p>
<ul>
<li><p>Local Storage</p>
</li>
<li><p>Session Storage</p>
</li>
<li><p>Cookies</p>
</li>
</ul>
<h2>Step 5: Client Sends Token</h2>
<p>Whenever a protected route is accessed:</p>
<pre><code class="language-plaintext">Authorization: Bearer jwt_token_here
</code></pre>
<h1>JWT Authentication Flow Diagram</h1>
<pre><code class="language-plaintext">+--------+        Login Request        +--------+
| Client | --------------------------&gt; | Server |
+--------+                             +--------+
     ^                                      |
     |                                      |
     |          JWT Token                   |
     +--------------------------------------+

Client stores token

Future Requests:

Client ---- JWT Token ----&gt; Server

Server verifies token

Valid Token?
   |
   +-- Yes -&gt; Allow Access
   |
   +-- No -&gt; Reject Request
</code></pre>
<h1>Creating JWT Authentication in Node.js</h1>
<p>Install required packages:</p>
<pre><code class="language-plaintext">npm install jsonwebtoken bcrypt
</code></pre>
<h1>Generating a JWT</h1>
<pre><code class="language-plaintext">const jwt = require("jsonwebtoken");

const token = jwt.sign(
  { userId: 1 },
  "secretKey",
  { expiresIn: "1h" }
);

console.log(token);
</code></pre>
<h1>Verifying a JWT</h1>
<pre><code class="language-plaintext">const decoded = jwt.verify(
  token,
  "secretKey"
);

console.log(decoded);
</code></pre>
<p>If verification succeeds, user data is returned.</p>
<p>If verification fails, an error is thrown.</p>
<h1>Sending Token with Requests</h1>
<p>The token is usually sent in the Authorization header.</p>
<pre><code class="language-plaintext">GET /profile

Authorization: Bearer jwt_token_here
</code></pre>
<p>The word <strong>Bearer</strong> simply means:</p>
<blockquote>
<p>"I am sending an access token."</p>
</blockquote>
<h1>Protecting Routes Using JWT</h1>
<p>Some routes should only be accessible to logged-in users.</p>
<p>Examples:</p>
<ul>
<li><p>User Profile</p>
</li>
<li><p>Dashboard</p>
</li>
<li><p>Orders</p>
</li>
<li><p>Settings</p>
</li>
</ul>
<p>We can create middleware to verify the token.</p>
<pre><code class="language-plaintext">const jwt = require("jsonwebtoken");

function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;

  const token = authHeader?.split(" ")[1];

  if (!token) {
    return res
      .status(401)
      .json({ message: "Token missing" });
  }

  try {
    const decoded = jwt.verify(
      token,
      "secretKey"
    );

    req.user = decoded;

    next();
  } catch (error) {
    return res
      .status(401)
      .json({ message: "Invalid token" });
  }
}
</code></pre>
<h1>Using Protected Routes</h1>
<pre><code class="language-plaintext">app.get(
  "/profile",
  authenticate,
  (req, res) =&gt; {
    res.json({
      message: "Welcome User",
      user: req.user,
    });
  }
);
</code></pre>
<p>If the token is valid:</p>
<pre><code class="language-plaintext">{
  "message": "Welcome User"
}
</code></pre>
<p>Otherwise:</p>
<pre><code class="language-plaintext">{
  "message": "Invalid token"
}
</code></pre>
<h1>Token Validation Lifecycle</h1>
<pre><code class="language-plaintext">User Login
    |
    v
Generate JWT
    |
    v
Send JWT To Client
    |
    v
Client Stores JWT
    |
    v
Client Sends JWT
    |
    v
Server Verifies JWT
    |
    +---- Valid ----&gt; Access Granted
    |
    +---- Invalid ---&gt; Access Denied
</code></pre>
<h1>Advantages of JWT</h1>
<ul>
<li><p>Stateless authentication</p>
</li>
<li><p>Fast verification</p>
</li>
<li><p>Works well with APIs</p>
</li>
<li><p>Easy to scale applications</p>
</li>
<li><p>Can be used across different services</p>
</li>
<li><p>Reduces server-side session storage</p>
</li>
</ul>
<h1>Limitations of JWT</h1>
<ul>
<li><p>Tokens cannot be easily revoked before expiration</p>
</li>
<li><p>Larger than session IDs</p>
</li>
<li><p>Incorrect handling can create security risks</p>
</li>
</ul>
<p>For most modern web applications, JWT remains one of the most popular authentication methods.</p>
<h1>Conclusion</h1>
<p>Authentication is an essential part of modern web applications. JWT provides a simple and scalable way to authenticate users without storing sessions on the server.</p>
<p>The basic idea is straightforward:</p>
<ul>
<li><p>User logs in</p>
</li>
<li><p>Server generates a JWT</p>
</li>
<li><p>Client stores the token</p>
</li>
<li><p>Client sends the token with requests</p>
</li>
<li><p>Server verifies the token</p>
</li>
<li><p>Protected resources become accessible</p>
</li>
</ul>
<p>Once you understand this flow, implementing authentication in Node.js becomes much easier and you'll be ready to build secure APIs and full-stack applications.</p>
]]></content:encoded></item><item><title><![CDATA[Creating Routes and Handling Requests with Express.js]]></title><description><![CDATA[Introduction
When building backend applications with Node.js, handling routes, requests, and responses using only the core http module becomes repetitive and complex. That’s where Express.js comes in.]]></description><link>https://newcohortblog2026.hashnode.dev/creating-routes-and-handling-requests-with-express-js</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/creating-routes-and-handling-requests-with-express-js</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Tue, 16 Jun 2026 08:11:42 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>When building backend applications with Node.js, handling routes, requests, and responses using only the core <code>http</code> module becomes repetitive and complex. That’s where Express.js comes in.</p>
<p>In this article, we will understand:</p>
<ul>
<li><p>What Express.js is</p>
</li>
<li><p>Why it simplifies Node.js development</p>
</li>
<li><p>How to create a first server</p>
</li>
<li><p>Handling GET and POST requests</p>
</li>
<li><p>Sending responses properly</p>
</li>
<li><p>Difference between raw Node.js server and Express</p>
</li>
</ul>
<h2>What is Express.js?</h2>
<p>Express.js is a minimal and fast web framework built on top of Node.js.</p>
<p>It provides a simple way to:</p>
<ul>
<li><p>Create servers</p>
</li>
<li><p>Define routes</p>
</li>
<li><p>Handle requests and responses</p>
</li>
<li><p>Build APIs quickly</p>
</li>
</ul>
<h2>Why Express simplifies Node.js development</h2>
<p>Without Express, Node.js requires manual handling of:</p>
<ul>
<li><p>Routing logic</p>
</li>
<li><p>Request parsing</p>
</li>
<li><p>Response formatting</p>
</li>
</ul>
<p>With Express, everything becomes clean and structured.</p>
<h3>Key benefits:</h3>
<ul>
<li><p>Less boilerplate code</p>
</li>
<li><p>Easy routing system</p>
</li>
<li><p>Built-in middleware support</p>
</li>
<li><p>Faster API development</p>
</li>
</ul>
<h2>Creating your first Express server</h2>
<h3>Step 1: Install Express</h3>
<pre><code class="language-plaintext">npm install express
</code></pre>
<h3>Step 2: Create server file</h3>
<pre><code class="language-plaintext">const express = require("express");

const app = express();

app.listen(3000, () =&gt; {
  console.log("Server is running on port 3000");
});
</code></pre>
<p>Now your server is running on:</p>
<pre><code class="language-plaintext">http://localhost:3000
</code></pre>
<h2>Handling GET requests</h2>
<p>GET requests are used to fetch data.</p>
<pre><code class="language-plaintext">app.get("/", (req, res) =&gt; {
  res.send("Hello from Express GET request!");
});
</code></pre>
<h3>Example route:</h3>
<pre><code class="language-plaintext">GET /home
</code></pre>
<pre><code class="language-plaintext">app.get("/home", (req, res) =&gt; {
  res.send("Welcome to Home Page");
});
</code></pre>
<h2>Handling POST requests</h2>
<p>POST requests are used to send data to the server.</p>
<h3>Enable JSON parsing middleware:</h3>
<pre><code class="language-plaintext">app.use(express.json());
</code></pre>
<h3>POST route example:</h3>
<pre><code class="language-plaintext">app.post("/user", (req, res) =&gt; {
  const user = req.body;

  res.send({
    message: "User received successfully",
    data: user
  });
});
</code></pre>
<p>Sending responses in Express</p>
<p>Express provides multiple ways to send responses:</p>
<ol>
<li><p>Plain text res.send("Hello World");</p>
</li>
<li><p>JSON response res.json({ success: true, message: "Data fetched" });</p>
</li>
<li><p>Status codes with response res.status(201).json({ message: "Created successfully" });</p>
</li>
</ol>
<h2>Raw Node.js vs Express.js comparison</h2>
<h3>Without Express (Raw Node.js)</h3>
<pre><code class="language-plaintext">const http = require("http");

const server = http.createServer((req, res) =&gt; {
  if (req.url === "/" &amp;&amp; req.method === "GET") {
    res.end("Hello from Node");
  }
});

server.listen(3000);
</code></pre>
<h3>With Express</h3>
<pre><code class="language-plaintext">const express = require("express");
const app = express();

app.get("/", (req, res) =&gt; {
  res.send("Hello from Express");
});

app.listen(3000);
</code></pre>
<h3>Key difference:</h3>
<ul>
<li><p>Node.js → manual routing, more code</p>
</li>
<li><p>Express → clean routing, less code</p>
</li>
</ul>
<h2>Request → Response Flow (Concept)</h2>
<pre><code class="language-plaintext">Client Request
     ↓
Express Router
     ↓
Route Handler Function
     ↓
Response Sent (res.send / res.json)
</code></pre>
<h2>Express Routing Structure</h2>
<pre><code class="language-plaintext">app
 ├── GET /home
 ├── GET /about
 ├── POST /user
 └── DELETE /user/:id
</code></pre>
<p>Each route handles a specific request type and URL</p>
]]></content:encoded></item><item><title><![CDATA[Synchronous vs Asynchronous JavaScript]]></title><description><![CDATA[Introduction
Imagine you are standing in a queue at a bank.
The cashier is serving one person at a time. Until the current person's work is finished, nobody else can be served.
This is how synchronous]]></description><link>https://newcohortblog2026.hashnode.dev/synchronous-vs-asynchronous-javascript</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/synchronous-vs-asynchronous-javascript</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Mon, 15 Jun 2026 06:53:57 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Imagine you are standing in a queue at a bank.</p>
<p>The cashier is serving one person at a time. Until the current person's work is finished, nobody else can be served.</p>
<p>This is how <strong>synchronous execution</strong> works.</p>
<p>Now imagine you order food online. After placing the order, you continue watching a movie while the restaurant prepares your food. When the food is ready, you receive it.</p>
<p>This is how <strong>asynchronous execution</strong> works.</p>
<p>JavaScript uses both approaches, but asynchronous programming is one of the most important concepts every developer must understand.</p>
<p>In this article, we'll learn:</p>
<ul>
<li><p>What synchronous code means</p>
</li>
<li><p>What asynchronous code means</p>
</li>
<li><p>Why JavaScript needs asynchronous behavior</p>
</li>
<li><p>Blocking vs non-blocking code</p>
</li>
<li><p>Real-world examples using timers and API calls</p>
</li>
<li><p>How JavaScript handles asynchronous tasks</p>
</li>
</ul>
<h1>The Problem</h1>
<p>Computers execute instructions one after another.</p>
<p>Suppose a program has to:</p>
<ol>
<li><p>Display user information</p>
</li>
<li><p>Fetch data from a server</p>
</li>
<li><p>Update the UI</p>
</li>
</ol>
<p>Fetching data from a server may take several seconds.</p>
<p>If JavaScript waits for that operation to finish before moving ahead, the entire application becomes slow and unresponsive.</p>
<p>This is the problem asynchronous programming solves.</p>
<h1>What is Synchronous JavaScript?</h1>
<p>Synchronous means:</p>
<blockquote>
<p>Execute one task at a time in order.</p>
</blockquote>
<p>The next line of code cannot run until the current line finishes execution.</p>
<h3>Example</h3>
<pre><code class="language-plaintext">console.log("Step 1");

console.log("Step 2");

console.log("Step 3");
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Step 1
Step 2
Step 3
</code></pre>
<p>Execution happens exactly in the order the code is written.</p>
<h1>How Synchronous Execution Works</h1>
<h3>Timeline</h3>
<pre><code class="language-plaintext">Start
  |
  v
Step 1
  |
  v
Step 2
  |
  v
Step 3
  |
  v
 End
</code></pre>
<p>Each task must finish before the next task starts.</p>
<h1>What is Asynchronous JavaScript?</h1>
<p>Asynchronous means:</p>
<blockquote>
<p>Start a task and continue executing other code without waiting for that task to finish.</p>
</blockquote>
<p>When the task completes, JavaScript handles the result later.</p>
<h1>Example Using setTimeout</h1>
<pre><code class="language-plaintext">console.log("Start");

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

console.log("End");
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Start
End
Timer Finished
</code></pre>
<p>Many beginners expect:</p>
<pre><code class="language-plaintext">Start
Timer Finished
End
</code></pre>
<p>But that does not happen.</p>
<p>JavaScript does not wait for the timer.</p>
<p>Instead, it continues executing the remaining code.</p>
<h1>Why Does JavaScript Need Asynchronous Behavior?</h1>
<p>JavaScript runs on a single thread.</p>
<p>This means it can do only one thing at a time.</p>
<p>If JavaScript waited for every slow operation, websites would freeze.</p>
<p>Examples of slow operations:</p>
<ul>
<li><p>API requests</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>Reading files</p>
</li>
<li><p>Network requests</p>
</li>
<li><p>Timers</p>
</li>
</ul>
<p>Without asynchronous programming, users would have a terrible experience.</p>
<h1>Real-Life Example</h1>
<p>Suppose you open Instagram.</p>
<p>The application needs to:</p>
<ul>
<li><p>Load posts</p>
</li>
<li><p>Load profile data</p>
</li>
<li><p>Load comments</p>
</li>
<li><p>Load notifications</p>
</li>
</ul>
<p>Fetching all this data takes time.</p>
<p>If JavaScript waited for each request to complete before doing anything else, the app would feel extremely slow.</p>
<p>Instead, requests are handled asynchronously.</p>
<p>The UI remains responsive while data loads in the background.</p>
<h1>Blocking Code</h1>
<p>Blocking code prevents other code from executing until the current task finishes.</p>
<h3>Example</h3>
<pre><code class="language-plaintext">function longTask() {
  const start = Date.now();

  while (Date.now() - start &lt; 5000) {
    // Wait 5 seconds
  }
}

console.log("Start");

longTask();

console.log("End");
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Start
(Wait 5 seconds)
End
</code></pre>
<p>The program becomes stuck for 5 seconds.</p>
<p>This is called blocking behavior.</p>
<h1>Problems with Blocking Code</h1>
<p>Blocking code can cause:</p>
<ul>
<li><p>Slow applications</p>
</li>
<li><p>Frozen UI</p>
</li>
<li><p>Poor user experience</p>
</li>
<li><p>Delayed user interactions</p>
</li>
</ul>
<p>Imagine clicking a button and waiting several seconds before the page responds.</p>
<p>Users would quickly leave the website.</p>
<h1>Non-Blocking Code</h1>
<p>Non-blocking code allows JavaScript to continue executing while waiting for a task to finish.</p>
<h3>Example</h3>
<pre><code class="language-plaintext">console.log("Start");

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

console.log("End");
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Start
End
Task Completed
</code></pre>
<p>The application remains responsive.</p>
<h1>API Call Example</h1>
<p>Fetching data from a server is a common asynchronous operation.</p>
<pre><code class="language-plaintext">fetch("https://jsonplaceholder.typicode.com/users")
  .then(response =&gt; response.json())
  .then(data =&gt; {
    console.log(data);
  });

console.log("Fetching data...");
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Fetching data...
[Users Data]
</code></pre>
<p>JavaScript starts the request and immediately continues executing other code.</p>
<p>When data arrives, the callback runs.</p>
<h1>Understanding the Task Queue</h1>
<p>When an asynchronous operation finishes, JavaScript does not execute it immediately.</p>
<p>Instead, it places the callback inside a queue.</p>
<p>The Event Loop checks:</p>
<ol>
<li><p>Is the Call Stack empty?</p>
</li>
<li><p>If yes, move tasks from the queue to the Call Stack.</p>
</li>
</ol>
<h3>Simplified Flow</h3>
<pre><code class="language-plaintext">Async Task
     |
     v
Task Queue
     |
     v
Event Loop
     |
     v
Call Stack
</code></pre>
<p>This mechanism makes asynchronous JavaScript possible.</p>
<h1>Synchronous vs Asynchronous</h1>
<table>
<thead>
<tr>
<th>Synchronous</th>
<th>Asynchronous</th>
</tr>
</thead>
<tbody><tr>
<td>Executes one task at a time</td>
<td>Can start a task and continue other work</td>
</tr>
<tr>
<td>Blocking behavior</td>
<td>Non-blocking behavior</td>
</tr>
<tr>
<td>Waits for completion</td>
<td>Does not wait</td>
</tr>
<tr>
<td>Simpler to understand</td>
<td>More powerful for real applications</td>
</tr>
<tr>
<td>Can freeze applications</td>
<td>Keeps applications responsive</td>
</tr>
</tbody></table>
<h1>Visual Comparison</h1>
<h2>Synchronous</h2>
<pre><code class="language-plaintext">Task 1
  ↓
Task 2
  ↓
Task 3
  ↓
Task 4
</code></pre>
<p>Everything happens one after another.</p>
<h2>Asynchronous</h2>
<pre><code class="language-plaintext">Start Task
     |
     +------&gt; Continue Other Work
     |
Task Completes Later
     |
     v
Execute Callback
</code></pre>
<p>The program remains active while waiting.</p>
<h1>When Do We Use Asynchronous Programming?</h1>
<p>Common scenarios include:</p>
<ul>
<li><p>API requests</p>
</li>
<li><p>Database operations</p>
</li>
<li><p>Timers</p>
</li>
<li><p>File reading</p>
</li>
<li><p>Uploading files</p>
</li>
<li><p>Downloading images</p>
</li>
<li><p>Chat applications</p>
</li>
<li><p>Real-time notifications</p>
</li>
</ul>
<p>Modern web applications rely heavily on asynchronous programming.</p>
<h1>Conclusion</h1>
<p>Synchronous code executes line by line and waits for each task to finish before moving to the next one.</p>
<p>Asynchronous code allows JavaScript to start a task and continue doing other work without waiting.</p>
<p>Because JavaScript runs on a single thread, asynchronous behavior is essential for handling slow operations like API calls, database requests, timers, and file operations without freezing the application.</p>
<p>Understanding synchronous and asynchronous programming is the first step toward learning Promises, Async/Await, the Event Loop, and advanced JavaScript concepts.</p>
]]></content:encoded></item><item><title><![CDATA[Async/Await in JavaScript: Writing Cleaner Asynchronous Code]]></title><description><![CDATA[Imagine you order a pizza online.
You place the order and then keep staring at the door until the pizza arrives.
Sounds strange, right?
Instead, you place the order, continue watching a movie, and whe]]></description><link>https://newcohortblog2026.hashnode.dev/async-await-in-javascript-writing-cleaner-asynchronous-code</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/async-await-in-javascript-writing-cleaner-asynchronous-code</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Sat, 13 Jun 2026 11:07:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/652623b8ae95eafcc8c9ed7b/effe9a08-466b-4fe0-8836-b81c6d7663f0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Imagine you order a pizza online.</p>
<p>You place the order and then keep staring at the door until the pizza arrives.</p>
<p>Sounds strange, right?</p>
<p>Instead, you place the order, continue watching a movie, and when the pizza arrives, you receive it.</p>
<p>This is exactly how asynchronous programming works in JavaScript.</p>
<p>Some tasks take time:</p>
<ul>
<li><p>Fetching data from an API</p>
</li>
<li><p>Reading files</p>
</li>
<li><p>Uploading images</p>
</li>
<li><p>Accessing a database</p>
</li>
</ul>
<p>JavaScript does not stop the entire application while waiting for these tasks to finish. Instead, it continues doing other work and handles the result when it becomes available.</p>
<p>In this article, we'll understand why <code>async/await</code> was introduced, how it works, and why it makes asynchronous code easier to read and maintain.</p>
<h2>The Problem Before Async/Await</h2>
<p>Let's say we want to fetch user data from an API.</p>
<p>Before async/await, developers mainly used Promises.</p>
<pre><code class="language-plaintext">fetch("https://api.example.com/user")
  .then(response =&gt; response.json())
  .then(data =&gt; {
    console.log(data);
  })
  .catch(error =&gt; {
    console.log(error);
  });
</code></pre>
<p>This works perfectly.</p>
<p>But when multiple asynchronous operations are involved, code can become difficult to read.</p>
<pre><code class="language-plaintext">fetchUser()
  .then(user =&gt; {
    return fetchOrders(user.id);
  })
  .then(orders =&gt; {
    return fetchPaymentDetails(orders);
  })
  .then(payment =&gt; {
    console.log(payment);
  })
  .catch(error =&gt; {
    console.log(error);
  });
</code></pre>
<p>As the application grows, these chained <code>.then()</code> calls become harder to understand.</p>
<p>Developers wanted a cleaner way to write asynchronous code that looked more like normal synchronous code.</p>
<p>This led to the introduction of <strong>async/await</strong>.</p>
<h2>What is Async/Await?</h2>
<p>Async/await is a feature built on top of Promises.</p>
<p>It does not replace Promises.</p>
<p>Instead, it provides a cleaner syntax for working with them.</p>
<p>This is why async/await is often called:</p>
<blockquote>
<p>Syntactic Sugar for Promises</p>
</blockquote>
<p>The underlying mechanism still uses Promises.</p>
<p>Async/await simply makes the code easier to read and write.</p>
<h2>Understanding the async Keyword</h2>
<p>The <code>async</code> keyword is used before a function declaration.</p>
<pre><code class="language-plaintext">async function greet() {
  return "Hello";
}
</code></pre>
<p>Even though we're returning a string, JavaScript automatically wraps it inside a Promise.</p>
<pre><code class="language-plaintext">greet().then(data =&gt; console.log(data));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello
</code></pre>
<p>Behind the scenes:</p>
<pre><code class="language-plaintext">async function greet() {
  return Promise.resolve("Hello");
}
</code></pre>
<p>So an async function always returns a Promise.</p>
<h2>Understanding the await Keyword</h2>
<p>The <code>await</code> keyword pauses the execution of an async function until a Promise is resolved.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function getData() {
  return new Promise(resolve =&gt; {
    setTimeout(() =&gt; {
      resolve("Data Received");
    }, 2000);
  });
}
</code></pre>
<p>Using await:</p>
<pre><code class="language-plaintext">async function fetchData() {
  const result = await getData();

  console.log(result);
}

fetchData();
</code></pre>
<p>Output after 2 seconds:</p>
<pre><code class="language-plaintext">Data Received
</code></pre>
<h2>How Await Works</h2>
<p>Let's understand the flow.</p>
<pre><code class="language-plaintext">async function fetchData() {
  console.log("Start");

  const result = await getData();

  console.log(result);

  console.log("End");
}
</code></pre>
<p>Execution Flow:</p>
<ol>
<li><p>"Start" is printed.</p>
</li>
<li><p><code>getData()</code> starts running.</p>
</li>
<li><p><code>await</code> pauses the function.</p>
</li>
<li><p>JavaScript continues handling other tasks.</p>
</li>
<li><p>Promise resolves.</p>
</li>
<li><p>Execution resumes.</p>
</li>
<li><p>Result is printed.</p>
</li>
<li><p>"End" is printed.</p>
</li>
</ol>
<p>Output:</p>
<pre><code class="language-plaintext">Start
Data Received
End
</code></pre>
<p>The entire application is not blocked.</p>
<p>Only the current async function waits.</p>
<h2>Real-World Example: Fetching API Data</h2>
<pre><code class="language-plaintext">async function getUsers() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
  );

  const users = await response.json();

  console.log(users);
}

getUsers();
</code></pre>
<p>Let's understand what's happening:</p>
<h3>Step 1</h3>
<pre><code class="language-plaintext">const response = await fetch(url);
</code></pre>
<p>JavaScript waits for the API response.</p>
<h3>Step 2</h3>
<pre><code class="language-plaintext">const users = await response.json();
</code></pre>
<p>JavaScript waits for JSON conversion.</p>
<h3>Step 3</h3>
<pre><code class="language-plaintext">console.log(users);
</code></pre>
<p>The user data is displayed.</p>
<p>The code reads almost like normal synchronous code.</p>
<h2>Error Handling with Async/Await</h2>
<p>Errors can occur while making API requests.</p>
<p>Examples:</p>
<ul>
<li><p>Internet connection failure</p>
</li>
<li><p>Invalid URL</p>
</li>
<li><p>Server error</p>
</li>
<li><p>Database issue</p>
</li>
</ul>
<p>We use <code>try...catch</code> to handle such errors.</p>
<pre><code class="language-plaintext">async function getUsers() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users"
    );

    const data = await response.json();

    console.log(data);
  } catch (error) {
    console.log("Error:", error.message);
  }
}

getUsers();
</code></pre>
<p>If something goes wrong, execution moves directly to the <code>catch</code> block.</p>
<h2>Example with Custom Error</h2>
<pre><code class="language-plaintext">async function getData() {
  try {
    throw new Error("Something went wrong");
  } catch (error) {
    console.log(error.message);
  }
}

getData();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Something went wrong
</code></pre>
<h2>Comparison Table</h2>
<table>
<thead>
<tr>
<th>Promise</th>
<th>Async/Await</th>
</tr>
</thead>
<tbody><tr>
<td>Uses <code>.then()</code> and <code>.catch()</code></td>
<td>Uses <code>async</code> and <code>await</code></td>
</tr>
<tr>
<td>Can become difficult to read with long chains</td>
<td>Looks cleaner and simpler</td>
</tr>
<tr>
<td>Good for chaining operations</td>
<td>Easier for sequential operations</td>
</tr>
<tr>
<td>Error handling through <code>.catch()</code></td>
<td>Error handling through <code>try...catch</code></td>
</tr>
<tr>
<td>More nested code</td>
<td>More readable code</td>
</tr>
</tbody></table>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript: Try, Catch, Finally]]></title><description><![CDATA[Imagine you're building a banking application.
A user clicks the "Check Balance" button. Your application tries to fetch data from the server, but suddenly the internet connection is lost.
What should]]></description><link>https://newcohortblog2026.hashnode.dev/error-handling-in-javascript-try-catch-finally</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/error-handling-in-javascript-try-catch-finally</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Sat, 13 Jun 2026 02:58:33 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you're building a banking application.</p>
<p>A user clicks the <strong>"Check Balance"</strong> button. Your application tries to fetch data from the server, but suddenly the internet connection is lost.</p>
<p>What should happen?</p>
<ul>
<li><p>Should the application crash?</p>
</li>
<li><p>Should users see a blank screen?</p>
</li>
<li><p>Should it show a helpful error message?</p>
</li>
</ul>
<p>This is where <strong>Error Handling</strong> comes into the picture.</p>
<p>In JavaScript, errors are unavoidable. Servers can fail, APIs can stop responding, users can enter invalid data, and bugs can appear unexpectedly.</p>
<p>A good developer doesn't try to eliminate every error. Instead, they handle errors gracefully so the application continues to work properly.</p>
<p>In this article, we'll learn what errors are, how to use <code>try</code>, <code>catch</code>, and <code>finally</code>, how to throw custom errors, and why error handling is essential in real-world applications</p>
<h2>The Problem: Applications Can Crash</h2>
<p>Imagine you're building an online shopping application.</p>
<p>A user clicks the "View Product" button.</p>
<p>Your code tries to fetch product details from a server:</p>
<pre><code class="language-plaintext">const product = getProductDetails();
console.log(product.name);
</code></pre>
<p>What if the server is down?</p>
<p>What if the product doesn't exist?</p>
<p>What if <code>product</code> becomes <code>undefined</code>?</p>
<p>JavaScript will throw an error, and your program may stop executing.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const user = undefined;

console.log(user.name);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">TypeError: Cannot read properties of undefined
</code></pre>
<p>Without proper handling, the application may break and provide a poor user experience.</p>
<h2>What Are Errors in JavaScript?</h2>
<h2>An error is something that prevents JavaScript from executing code correctly.</h2>
<p>Common types of errors include:</p>
<h3>1. Syntax Error</h3>
<p><strong>Occurs when JavaScript code is written incorrectly.</strong></p>
<pre><code class="language-plaintext">console.log("Hello"
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">SyntaxError: missing ) after argument list
</code></pre>
<h3>2. Reference Error</h3>
<p>Occurs when a variable doesn't exist.</p>
<pre><code class="language-plaintext">console.log(username);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">ReferenceError: username is not defined
</code></pre>
<h3>3. Type Error</h3>
<p>Occurs when an operation is performed on an invalid type.</p>
<pre><code class="language-plaintext">const user = null;

console.log(user.name);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">TypeError: Cannot read properties of null
</code></pre>
<h3>4. Range Error</h3>
<p>Occurs when a value is outside the allowed range.</p>
<pre><code class="language-plaintext">const num = 10;

num.toPrecision(500);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">RangeError
</code></pre>
<h2>Why Do We Need Error Handling?</h2>
<p>Imagine a banking application.</p>
<p>A user tries to transfer money.</p>
<p>If an error occurs and the application crashes, the user won't know what happened.</p>
<p>Instead of crashing, we should:</p>
<ul>
<li><p>Detect errors</p>
</li>
<li><p>Handle them gracefully</p>
</li>
<li><p>Show meaningful messages</p>
</li>
<li><p>Continue running the application</p>
</li>
</ul>
<p>This is exactly what <code>try</code> and <code>catch</code> help us do.</p>
<h2>Using Try and Catch</h2>
<p>The <code>try</code> block contains code that may throw an error.</p>
<p>The <code>catch</code> block handles the error if one occurs.</p>
<p>Syntax:</p>
<pre><code class="language-plaintext">try {
  // risky code
} catch (error) {
  // handle error
}
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">try {
  const user = null;

  console.log(user.name);
} catch (error) {
  console.log("Something went wrong");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Something went wrong
</code></pre>
<p>Instead of crashing, the program handles the error gracefully.</p>
<h2>Understanding the Error Object</h2>
<p>The <code>catch</code> block receives an error object.</p>
<pre><code class="language-plaintext">try {
  console.log(userName);
} catch (error) {
  console.log(error);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">ReferenceError: userName is not defined
</code></pre>
<p>Useful properties:</p>
<pre><code class="language-plaintext">try {
  console.log(userName);
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">ReferenceError
userName is not defined
</code></pre>
<p>These details are extremely useful while debugging applications.</p>
<h2>Real-World Example</h2>
<p>Suppose we're parsing JSON data received from an API.</p>
<pre><code class="language-plaintext">try {
  const data = JSON.parse("invalid json");

  console.log(data);
} catch (error) {
  console.log("Invalid JSON received");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Invalid JSON received
</code></pre>
<p>Without <code>try-catch</code>, the application would throw an error and stop.</p>
<h2>The Finally Block</h2>
<p>Sometimes we need code that should execute whether an error occurs or not.</p>
<p>For this purpose, JavaScript provides the <code>finally</code> block.</p>
<p>Syntax:</p>
<pre><code class="language-plaintext">try {
  // code
} catch (error) {
  // handle error
} finally {
  // always runs
}
</code></pre>
<h3>Example of Finally</h3>
<pre><code class="language-plaintext">try {
  console.log("Connecting to server");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("Connection closed");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Connecting to server
Connection closed
</code></pre>
<p>Even when an error occurs:</p>
<pre><code class="language-plaintext">try {
  console.log(userName);
} catch (error) {
  console.log("Error handled");
} finally {
  console.log("Cleanup completed");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Error handled
Cleanup completed
</code></pre>
<p>The <code>finally</code> block always executes.</p>
<h3>Real-World Use Cases of Finally</h3>
<p>Common scenarios:</p>
<ul>
<li><p>Closing database connections</p>
</li>
<li><p>Hiding loading spinners</p>
</li>
<li><p>Releasing resources</p>
</li>
<li><p>Cleaning temporary files</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-plaintext">showLoader();

try {
  fetchData();
} catch (error) {
  console.log("Failed to fetch data");
} finally {
  hideLoader();
}
</code></pre>
<p>No matter what happens, the loader is removed.</p>
<h2>Throwing Custom Errors</h2>
<p>JavaScript also allows developers to create their own errors using the <code>throw</code> keyword.</p>
<p>This is useful when business rules are violated.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const age = 15;

if (age &lt; 18) {
  throw new Error("You must be at least 18 years old");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Error: You must be at least 18 years old
</code></pre>
<hr />
<h3>Handling Custom Errors</h3>
<pre><code class="language-plaintext">try {
  const age = 15;

  if (age &lt; 18) {
    throw new Error("You must be at least 18 years old");
  }

  console.log("Access Granted");
} catch (error) {
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">You must be at least 18 years old
</code></pre>
<h2>Practical Example: ATM Withdrawal</h2>
<p>Imagine an ATM machine.</p>
<p>A user wants to withdraw ₹10,000.</p>
<p>Current balance is ₹5,000.</p>
<pre><code class="language-plaintext">try {
  const balance = 5000;
  const withdrawAmount = 10000;

  if (withdrawAmount &gt; balance) {
    throw new Error("Insufficient balance");
  }

  console.log("Withdrawal successful");
} catch (error) {
  console.log(error.message);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Insufficient balance
</code></pre>
<p>This is a perfect example of a custom error.</p>
<h2>Error Handling Flow</h2>
<pre><code class="language-plaintext">Program Starts
      |
      v
   try Block
      |
      |
 Error?
  /     \
Yes      No
 |         |
 v         v
catch    Skip
 Block   catch
   \      /
    \    /
     v  v
   finally
      |
      v
 Program Ends
</code></pre>
<h2>Why Error Handling Matters</h2>
<p>Good error handling provides several benefits:</p>
<h3>Better User Experience</h3>
<p><strong>Users see meaningful messages instead of broken applications.</strong></p>
<pre><code class="language-plaintext">"Unable to load data. Please try again."
</code></pre>
<p>Instead of:</p>
<pre><code class="language-plaintext">TypeError: Cannot read properties of undefined
</code></pre>
<h2>Easier Debugging</h2>
<p>Error details help developers quickly identify problems.</p>
<pre><code class="language-plaintext">console.log(error.name);
console.log(error.message);
</code></pre>
<h2>Prevents Application Crashes</h2>
<p>Applications continue running even when something goes wrong.</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[JavaScript provides two powerful operators that use the same syntax (...) but behave differently depending on where they are used.
Many beginners get confused because both Spread and Rest use three do]]></description><link>https://newcohortblog2026.hashnode.dev/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/spread-vs-rest-operators-in-javascript</guid><category><![CDATA[chaicode webdev cohort 2026]]></category><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Fri, 12 Jun 2026 14:04:02 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript provides two powerful operators that use the same syntax (<code>...</code>) but behave differently depending on where they are used.</p>
<p>Many beginners get confused because both Spread and Rest use three dots. The key difference is:</p>
<ul>
<li><p><strong>Spread Operator</strong> → Expands values</p>
</li>
<li><p><strong>Rest Operator</strong> → Collects values</p>
</li>
</ul>
<p>Let's understand them with simple examples.</p>
<h2>The Problem</h2>
<p>Imagine you have an array:</p>
<pre><code class="language-plaintext">const fruits = ["Apple", "Banana", "Mango"];
</code></pre>
<p>Sometimes you want to:</p>
<ul>
<li><p>Take elements out of an array individually</p>
</li>
<li><p>Merge arrays</p>
</li>
<li><p>Copy arrays or objects</p>
</li>
<li><p>Accept multiple function arguments</p>
</li>
</ul>
<p>JavaScript provides Spread and Rest operators to solve these problems easily.</p>
<h2>What is the Spread Operator?</h2>
<p>The Spread Operator (<code>...</code>) expands an iterable (such as an array or object) into individual elements.</p>
<p>Think of it like:</p>
<pre><code class="language-plaintext">Packed Box → Open Everything Inside
</code></pre>
<h3>Syntax</h3>
<pre><code class="language-plaintext">...value
</code></pre>
<h3>Spread with Arrays</h3>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">const numbers = [1, 2, 3];

console.log(...numbers);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">1 2 3
</code></pre>
<p>The array gets expanded into individual values.</p>
<h3>Copying an Array</h3>
<p><strong>Without Spread</strong></p>
<pre><code class="language-plaintext">const arr1 = [1, 2, 3];
const arr2 = arr1;
</code></pre>
<p>This creates a reference, not a copy.</p>
<p><strong>With Spread</strong></p>
<pre><code class="language-plaintext">const arr1 = [1, 2, 3];
const arr2 = [...arr1];

console.log(arr2);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">[1, 2, 3]
</code></pre>
<p>Now <code>arr2</code> is a new array.</p>
<h3>Merging Arrays</h3>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">const frontend = ["HTML", "CSS"];
const javascript = ["JavaScript", "React"];

const skills = [...frontend, ...javascript];

console.log(skills);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">["HTML", "CSS", "JavaScript", "React"]
</code></pre>
<p>Spread expands both arrays and combines them.</p>
<h3>Spread with Objects</h3>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">const user = {
  name: "Ashish",
  age: 24,
};

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

console.log(updatedUser);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">{
  name: "Ashish",
  age: 24,
  city: "Pune"
}
</code></pre>
<p>Spread copies existing properties and adds new ones.</p>
<h2>Real-World Use Case of Spread</h2>
<p>Updating React state:</p>
<pre><code class="language-plaintext">setUser({
  ...user,
  name: "Ashish Gaikwad",
});
</code></pre>
<p>Instead of rewriting the whole object, spread copies existing values and updates only the required property.</p>
<h2>What is the Rest Operator?</h2>
<p>The Rest Operator (<code>...</code>) collects multiple values into a single array.</p>
<p>Think of it like:</p>
<pre><code class="language-plaintext">Many Values → Pack Into One Box
</code></pre>
<p><strong>Syntax</strong></p>
<pre><code class="language-plaintext">...variable
</code></pre>
<h2>Rest in Function Parameters</h2>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">function addNumbers(...numbers) {
  console.log(numbers);
}

addNumbers(10, 20, 30, 40);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">[10, 20, 30, 40]
</code></pre>
<p>All arguments are collected into a single array.</p>
<h3>Sum Using Rest Operator</h3>
<pre><code class="language-plaintext">function sum(...numbers) {
  return numbers.reduce((acc, num) =&gt; acc + num, 0);
}

console.log(sum(1, 2, 3, 4, 5));
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">15
</code></pre>
<h3>Rest with Array Destructuring</h3>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">const colors = ["Red", "Blue", "Green", "Yellow"];

const [first, ...remaining] = colors;

console.log(first);
console.log(remaining);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">Red
["Blue", "Green", "Yellow"]
</code></pre>
<p>The first value is extracted and the rest are collected into an array.</p>
<h3>Rest with Objects</h3>
<p><strong>Example</strong></p>
<pre><code class="language-plaintext">const user = {
  name: "Ashish",
  age: 24,
  city: "Pune",
};

const { name, ...otherDetails } = user;

console.log(name);
console.log(otherDetails);
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-plaintext">Ashish

{
  age: 24,
  city: "Pune"
}
</code></pre>
<p>The remaining properties are collected into a new object.</p>
<h2>Spread vs Rest</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Spread Operator</th>
<th>Rest Operator</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Expands values</td>
<td>Collects values</td>
</tr>
<tr>
<td>Direction</td>
<td>One → Many</td>
<td>Many → One</td>
</tr>
<tr>
<td>Arrays</td>
<td>Expands elements</td>
<td>Collects remaining elements</td>
</tr>
<tr>
<td>Objects</td>
<td>Expands properties</td>
<td>Collects remaining properties</td>
</tr>
<tr>
<td>Functions</td>
<td>Pass arguments</td>
<td>Receive arguments</td>
</tr>
</tbody></table>
<h2>Visual Diagram</h2>
<h3><strong>Spread Operator</strong></h3>
<pre><code class="language-plaintext">Array
[1, 2, 3]

   ...
    ↓

1   2   3
</code></pre>
<p>Expands values.</p>
<h3>Rest Operator</h3>
<pre><code class="language-plaintext">1   2   3   4

   ...

    ↓

[1, 2, 3, 4]
</code></pre>
<p>Collects values.</p>
<h2>When to Use Spread</h2>
<p>Use Spread when you want to:</p>
<ul>
<li><p>Copy arrays</p>
</li>
<li><p>Copy objects</p>
</li>
<li><p>Merge arrays</p>
</li>
<li><p>Merge objects</p>
</li>
<li><p>Pass array elements as function arguments</p>
</li>
</ul>
<h2>When to Use Rest</h2>
<p>Use Rest when you want to:</p>
<ul>
<li><p>Accept unlimited function arguments</p>
</li>
<li><p>Gather remaining array elements</p>
</li>
<li><p>Gather remaining object properties</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Setting Up Your First Node.js Application Step-by-Step]]></title><description><![CDATA[Imagine you have learned JavaScript and can build logic in the browser. Now you want to create servers, APIs, and backend applications. The first question most beginners ask is:
"How do I start my fir]]></description><link>https://newcohortblog2026.hashnode.dev/setting-up-your-first-node-js-application-step-by-step</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/setting-up-your-first-node-js-application-step-by-step</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Cohort2026]]></category><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Fri, 12 Jun 2026 13:46:40 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you have learned JavaScript and can build logic in the browser. Now you want to create servers, APIs, and backend applications. The first question most beginners ask is:</p>
<p><strong>"How do I start my first Node.js application?"</strong></p>
<p>In this article, we'll learn how to install Node.js, verify the installation, understand the Node REPL, create our first JavaScript file, run it using Node, and finally build a simple Hello World server.</p>
<h2>The Problem</h2>
<p>JavaScript originally worked only inside browsers.</p>
<p>If you wanted to run JavaScript outside the browser, create servers, read files, or interact with databases, you couldn't do it.</p>
<p>For example:</p>
<pre><code class="language-plaintext">console.log("Hello World");
</code></pre>
<p>This code runs in Chrome, Firefox, or Edge.</p>
<p>But how can we run it directly from our computer's terminal?</p>
<p>This is where Node.js comes in.</p>
<h2>What is Node.js?</h2>
<p>Node.js is a JavaScript runtime that allows JavaScript code to run outside the browser.</p>
<p>Think of it like this:</p>
<ul>
<li><p>Browser = Runs JavaScript inside websites</p>
</li>
<li><p>Node.js = Runs JavaScript on your computer</p>
</li>
</ul>
<p>With Node.js, you can build:</p>
<ul>
<li><p>Backend APIs</p>
</li>
<li><p>Web servers</p>
</li>
<li><p>Real-time applications</p>
</li>
<li><p>Command-line tools</p>
</li>
<li><p>Full-stack applications</p>
</li>
</ul>
<h2>Installing Node.js</h2>
<p>Visit the official Node.js website:</p>
<p><a href="https://nodejs.org">https://nodejs.org</a></p>
<p>Download the LTS (Long-Term Support) version.</p>
<p>The installation process is similar across operating systems:</p>
<ol>
<li><p>Download Node.js</p>
</li>
<li><p>Run the installer</p>
</li>
<li><p>Follow the setup wizard</p>
</li>
<li><p>Complete installation</p>
</li>
</ol>
<p>After installation, Node.js and npm are installed automatically.</p>
<h3>What is npm?</h3>
<p>npm stands for Node Package Manager.</p>
<p>It helps us install and manage packages used in Node.js projects.</p>
<h2>Checking the Installation</h2>
<p>Open your terminal and run:</p>
<pre><code class="language-plaintext">node -v
</code></pre>
<p>Example output:</p>
<pre><code class="language-plaintext">v24.1.0
</code></pre>
<p>Now check npm:</p>
<pre><code class="language-plaintext">npm -v
</code></pre>
<p>Example output:</p>
<pre><code class="language-plaintext">11.2.0
</code></pre>
<p>If both commands show versions, Node.js is installed successfully.</p>
<h2>Understanding Node REPL</h2>
<p>Before creating files, let's understand REPL.</p>
<p>REPL stands for:</p>
<ul>
<li><p>Read</p>
</li>
<li><p>Evaluate</p>
</li>
<li><p>Print</p>
</li>
<li><p>Loop</p>
</li>
</ul>
<p>Node REPL is an interactive environment where you can execute JavaScript code directly from the terminal.</p>
<p>Start REPL:</p>
<pre><code class="language-plaintext">node
</code></pre>
<p>You will see something like:</p>
<pre><code class="language-plaintext">&gt;
</code></pre>
<p>Now type:</p>
<pre><code class="language-plaintext">2 + 3
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">5
</code></pre>
<p>Try:</p>
<pre><code class="language-plaintext">const name = "Ashish";
name
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">'Ashish'
</code></pre>
<p>Node immediately reads your code, executes it, prints the result, and waits for the next command.</p>
<p>That's why it's called REPL.</p>
<p>Exit REPL:</p>
<pre><code class="language-plaintext">.exit
</code></pre>
<p>or</p>
<pre><code class="language-plaintext">Ctrl + C
</code></pre>
<p>(two times)</p>
<h2>Creating Your First JavaScript File</h2>
<p>Create a file named:</p>
<pre><code class="language-plaintext">app.js
</code></pre>
<p>Add the following code:</p>
<pre><code class="language-plaintext">console.log("Hello from Node.js");
</code></pre>
<p>Save the file.</p>
<h2>Running the Script Using Node</h2>
<p>Open terminal in the same folder.</p>
<p>Run:</p>
<pre><code class="language-plaintext">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello from Node.js
</code></pre>
<p>Congratulations!</p>
<p>You just executed your first Node.js application.</p>
<h2>How Node Executes a Script</h2>
<p>The execution flow looks like this:</p>
<pre><code class="language-plaintext">app.js
   ↓
Node Runtime
   ↓
JavaScript Engine
   ↓
Output in Terminal
</code></pre>
<h3>Step-by-Step</h3>
<ol>
<li><p>Node reads the file.</p>
</li>
<li><p>Node sends JavaScript code to the JavaScript engine.</p>
</li>
<li><p>The engine executes the code.</p>
</li>
<li><p>Result appears in the terminal.</p>
</li>
</ol>
<h2>Building a Hello World Server</h2>
<p>Printing text is useful, but backend developers create servers.</p>
<p>Let's create our first web server.</p>
<p>Create a file:</p>
<pre><code class="language-plaintext">const http = require("http");

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

server.listen(3000, () =&gt; {
  console.log("Server running on port 3000");
});
</code></pre>
<h2>Understanding the Code</h2>
<h3>Import HTTP Module</h3>
<pre><code class="language-plaintext">const http = require("http");
</code></pre>
<p>Node provides a built-in HTTP module for creating servers.</p>
<h3>Create Server</h3>
<pre><code class="language-plaintext">const server = http.createServer((req, res) =&gt; {
  res.end("Hello World");
});
</code></pre>
<p>Whenever a request arrives:</p>
<ul>
<li><p><code>req</code> contains request information.</p>
</li>
<li><p><code>res</code> is used to send a response.</p>
</li>
</ul>
<h3>Start Listening</h3>
<pre><code class="language-plaintext">server.listen(3000);
</code></pre>
<p>The server starts listening on port 3000.</p>
<h2>Running the Server</h2>
<p>Execute:</p>
<pre><code class="language-plaintext">node app.js
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Server running on port 3000
</code></pre>
<p>Open your browser and visit:</p>
<pre><code class="language-plaintext">http://localhost:3000
</code></pre>
<p>You will see:</p>
<pre><code class="language-plaintext">Hello World
</code></pre>
<p>Your first Node.js server is now running successfully.</p>
<h2>Node Execution Flow</h2>
<p>The overall flow looks like this:</p>
<pre><code class="language-plaintext">Browser Request
       ↓
Node.js Server
       ↓
Request Handler
       ↓
Response Sent
       ↓
Browser Displays Result
</code></pre>
]]></content:encoded></item><item><title><![CDATA[String Polyfills and Common Interview Methods in JavaScript]]></title><description><![CDATA[Have you ever used methods like split(), includes(), startsWith(), or trim() and wondered how JavaScript actually performs these operations behind the scenes?
Most developers use built-in string metho]]></description><link>https://newcohortblog2026.hashnode.dev/string-polyfills-and-common-interview-methods-in-javascript</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/string-polyfills-and-common-interview-methods-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Cohort2026]]></category><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Fri, 12 Jun 2026 08:14:54 GMT</pubDate><content:encoded><![CDATA[<p>Have you ever used methods like <code>split()</code>, <code>includes()</code>, <code>startsWith()</code>, or <code>trim()</code> and wondered how JavaScript actually performs these operations behind the scenes?</p>
<p>Most developers use built-in string methods every day. However, in frontend interviews, especially for JavaScript roles, interviewers often go one step further and ask:</p>
<blockquote>
<p>"Can you implement this method yourself?"</p>
</blockquote>
<p>This is where understanding string polyfills becomes valuable.</p>
<p>In this article, we'll learn what string methods are, why developers write polyfills, how common string utilities work internally, and some popular interview questions related to strings</p>
<h2>The Problem</h2>
<p>Imagine you're building a JavaScript application and need to check whether a string contains a specific word.</p>
<p>You can simply write:</p>
<pre><code class="language-plaintext">const text = "JavaScript is awesome";

console.log(text.includes("awesome"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<p>Easy, right?</p>
<p>But what if this method didn't exist?</p>
<p>Could you build it yourself?</p>
<p>That's exactly what interviewers want to test.</p>
<p>They are not interested in whether you remember the method name.</p>
<p>They want to know whether you understand the logic behind it.</p>
<h2>What Are String Methods?</h2>
<p>String methods are built-in functions provided by JavaScript that allow us to manipulate and process text.</p>
<p>Examples:</p>
<pre><code class="language-plaintext">let name = "Ashish";
</code></pre>
<pre><code class="language-plaintext">name.toUpperCase();
name.toLowerCase();
name.includes("shi");
name.startsWith("A");
name.endsWith("h");
name.trim();
name.split("");
</code></pre>
<p>These methods help us perform common text operations without writing complex logic every time.</p>
<h2>Why Developers Write Polyfills</h2>
<h2>A polyfill is custom code that replicates the behavior of a built-in JavaScript method.</h2>
<p>Think of it as:</p>
<blockquote>
<p>"If JavaScript didn't provide this method, how would I create it myself?"</p>
</blockquote>
<p>Developers write polyfills to:</p>
<ul>
<li><p>Understand internal working of JavaScript methods</p>
</li>
<li><p>Support older browsers</p>
</li>
<li><p>Improve problem-solving skills</p>
</li>
<li><p>Prepare for interviews</p>
</li>
</ul>
<p>Many JavaScript interviews include questions like:</p>
<ul>
<li><p>Create your own <code>includes()</code></p>
</li>
<li><p>Implement <code>startsWith()</code></p>
</li>
<li><p>Build a custom <code>trim()</code></p>
</li>
<li><p>Create a custom <code>split()</code></p>
</li>
</ul>
<h2>How Built-in Methods Work Conceptually</h2>
<p>Let's understand the idea behind string processing.</p>
<h3>String Processing Flow</h3>
<pre><code class="language-plaintext">Input String
      │
Character Traversal
      │
Condition Checking
      │
Result Generation
      │
Return Output
</code></pre>
<p>Almost every string method follows this pattern.</p>
<p>The method reads characters one by one, performs some checks, and returns a result.</p>
<h2>Polyfill for includes()</h2>
<h3>Built-in Method</h3>
<pre><code class="language-plaintext">const text = "JavaScript";

console.log(text.includes("Script"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<h3>Logic</h3>
<ol>
<li><p>Traverse the string.</p>
</li>
<li><p>Check every possible position.</p>
</li>
<li><p>Compare characters.</p>
</li>
<li><p>If all characters match, return true.</p>
</li>
<li><p>Otherwise return false.</p>
</li>
</ol>
<h3>Polyfill</h3>
<pre><code class="language-plaintext">String.prototype.myIncludes = function(search) {
  const str = this;

  for (let i = 0; i &lt;= str.length - search.length; i++) {
    let match = true;

    for (let j = 0; j &lt; search.length; j++) {
      if (str[i + j] !== search[j]) {
        match = false;
        break;
      }
    }

    if (match) {
      return true;
    }
  }

  return false;
};
</code></pre>
<p>Usage:</p>
<pre><code class="language-plaintext">console.log("JavaScript".myIncludes("Script"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<h2>Polyfill for startsWith()</h2>
<h3>Built-in Method</h3>
<pre><code class="language-plaintext">console.log("JavaScript".startsWith("Java"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<h3>Logic</h3>
<p>Compare characters from the beginning of the string</p>
<h3>Polyfill</h3>
<pre><code class="language-plaintext">String.prototype.myStartsWith = function(search) {
  const str = this;

  for (let i = 0; i &lt; search.length; i++) {
    if (str[i] !== search[i]) {
      return false;
    }
  }

  return true;
};
</code></pre>
<p>Usage:</p>
<pre><code class="language-plaintext">console.log("JavaScript".myStartsWith("Java"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<h2>Polyfill for endsWith()</h2>
<h3>Built-in Method</h3>
<pre><code class="language-plaintext">console.log("JavaScript".endsWith("Script"));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<h3>Logic</h3>
<p>Start comparing from the end of both strings.</p>
<h3>Polyfill</h3>
<pre><code class="language-plaintext">String.prototype.myEndsWith = function(search) {
  const str = this;

  if (search.length &gt; str.length) {
    return false;
  }

  let start = str.length - search.length;

  for (let i = 0; i &lt; search.length; i++) {
    if (str[start + i] !== search[i]) {
      return false;
    }
  }

  return true;
};
</code></pre>
<h2>Polyfill for trim()</h2>
<h3>Built-in Method</h3>
<pre><code class="language-plaintext">const text = "   hello world   ";

console.log(text.trim());
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">hello world
</code></pre>
<h3>Logic</h3>
<p>Remove spaces from:</p>
<ul>
<li><p>Beginning</p>
</li>
<li><p>End</p>
</li>
</ul>
<p>Keep spaces in the middle unchanged.</p>
<h3>Polyfill</h3>
<pre><code class="language-plaintext">String.prototype.myTrim = function() {
  let start = 0;
  let end = this.length - 1;

  while (this[start] === " ") {
    start++;
  }

  while (this[end] === " ") {
    end--;
  }

  return this.slice(start, end + 1);
};
</code></pre>
<h2>Final Thoughts</h2>
<p>Most developers use methods like <code>includes()</code>, <code>startsWith()</code>, and <code>trim()</code> every day without thinking about what happens internally.</p>
<p>However, understanding the logic behind these methods helps you become a stronger JavaScript developer and perform better in interviews.</p>
<p>The next time you use a built-in string method, ask yourself:</p>
<blockquote>
<p>"If JavaScript didn't provide this method, could I build it myself?"</p>
</blockquote>
<p>If your answer is yes, you're developing the kind of problem-solving mindset that interviewers look for.</p>
]]></content:encoded></item><item><title><![CDATA[How Node.js Handles Multiple Requests with a Single Thread]]></title><description><![CDATA[Imagine you own a small restaurant.
Customers keep coming in and placing orders. One wants tea, another wants coffee, another wants a pizza, and someone else wants a burger.
Now imagine there is only ]]></description><link>https://newcohortblog2026.hashnode.dev/how-node-js-handles-multiple-requests-with-a-single-thread</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/how-node-js-handles-multiple-requests-with-a-single-thread</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Fri, 12 Jun 2026 03:03:41 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you own a small restaurant.</p>
<p>Customers keep coming in and placing orders. One wants tea, another wants coffee, another wants a pizza, and someone else wants a burger.</p>
<p>Now imagine there is only <strong>one chef</strong> in the kitchen.</p>
<p>At first, this sounds like a disaster.</p>
<p>How can one chef handle so many orders at the same time?</p>
<p>Surprisingly, that's exactly how Node.js works.</p>
<p>Even though Node.js runs JavaScript on a <strong>single thread</strong>, it can efficiently handle thousands of requests. Let's understand how.</p>
<h2>The Problem</h2>
<p>Most beginners hear this statement:</p>
<blockquote>
<p>"Node.js is single-threaded."</p>
</blockquote>
<p>Then a question immediately comes to mind:</p>
<p>"If there is only one thread, how can Node.js serve hundreds or thousands of users simultaneously?"</p>
<p>To answer this, we first need to understand the difference between a thread and a process</p>
<h2>Process vs Thread</h2>
<h3>Process</h3>
<p>A process is an independent running program.</p>
<p>For example:</p>
<ul>
<li><p>Chrome browser</p>
</li>
<li><p>VS Code</p>
</li>
<li><p>Spotify</p>
</li>
</ul>
<p>Each of these runs as a separate process.</p>
<p>Think of a process as an entire restaurant building.</p>
<hr />
<h3>Thread</h3>
<p>A thread is a worker inside a process.</p>
<p>A process can have one thread or multiple threads.</p>
<p>Think of threads as chefs working inside the restaurant.</p>
<p>Many traditional servers create multiple threads to handle multiple requests.</p>
<p>Node.js takes a different approach.</p>
<h2>Node.js is Single-Threaded</h2>
<p>Node.js uses a single main thread to execute JavaScript code.</p>
<p>This means:</p>
<ul>
<li><p>One call stack</p>
</li>
<li><p>One JavaScript execution thread</p>
</li>
<li><p>One event loop</p>
</li>
</ul>
<p>Only one JavaScript task runs at a time.</p>
<p>This sounds limiting, but Node.js becomes powerful because of its Event Loop.</p>
<h2>The Chef Analogy</h2>
<p>Let's return to our restaurant.</p>
<p>A customer orders pizza.</p>
<p>Instead of standing near the oven and waiting 20 minutes, the chef puts the pizza into the oven and starts taking another order.</p>
<p>While the oven is doing its work, the chef remains free.</p>
<p>When the pizza is ready, the chef serves it.</p>
<p>This is exactly how Node.js handles requests.</p>
<p>The main thread does not sit idle waiting for slow operations.</p>
<p>It delegates them and continues handling new requests.</p>
<h2>What is the Event Loop?</h2>
<p>The Event Loop is the heart of Node.js.</p>
<p>Its job is to continuously check:</p>
<ol>
<li><p>Is there any task waiting to be executed?</p>
</li>
<li><p>Is the call stack empty?</p>
</li>
<li><p>If yes, move the next task to execution.</p>
</li>
</ol>
<p>The event loop allows Node.js to manage many operations without creating a new thread for every request.</p>
<h2>How Multiple Requests are Handled</h2>
<p>Suppose three users send requests simultaneously.</p>
<pre><code class="language-plaintext">app.get("/user", (req, res) =&gt; {
  fs.readFile("user.txt", (err, data) =&gt; {
    res.send(data);
  });
});
</code></pre>
<h3>Step 1</h3>
<p>Request A arrives.</p>
<p>Node.js starts reading the file.</p>
<p>Since file reading is an I/O operation, Node.js delegates it to the system.</p>
<h3>Step 2</h3>
<p>Instead of waiting, Node.js immediately becomes available.</p>
<p>Request B arrives.</p>
<p>Node.js starts processing Request B.</p>
<h3>Step 3</h3>
<p>Request C arrives.</p>
<p>Node.js processes Request C as well.</p>
<h3>Step 4</h3>
<p>When file reading completes, the callback is placed into a queue.</p>
<p>The Event Loop picks it up and executes it.</p>
<p>The response is then sent to the client.</p>
<p>As a result:</p>
<ul>
<li><p>Requests are not blocked</p>
</li>
<li><p>The main thread remains free</p>
</li>
<li><p>Many users can be served efficiently</p>
</li>
</ul>
<h2>Delegating Work to Background Workers</h2>
<p>Node.js does not perform heavy I/O tasks itself.</p>
<p>Instead, it delegates work to:</p>
<ul>
<li><p>Operating System</p>
</li>
<li><p>libuv Thread Pool</p>
</li>
</ul>
<p>Examples:</p>
<ul>
<li><p>File system operations</p>
</li>
<li><p>Database communication</p>
</li>
<li><p>Network requests</p>
</li>
<li><p>DNS lookups</p>
</li>
<li><p>Some cryptographic operations</p>
</li>
</ul>
<p>While these tasks are running elsewhere, the main JavaScript thread remains available</p>
<h2>Event Loop + Worker Flow</h2>
<pre><code class="language-plaintext">Client Request
       |
       v
 Main Thread
       |
       v
 Delegates Task
       |
       v
 Worker Thread / OS
       |
       v
 Task Completed
       |
       v
 Callback Queue
       |
       v
 Event Loop
       |
       v
 Response Sent
</code></pre>
<h2>Single Thread Handling Multiple Requests</h2>
<pre><code class="language-plaintext">Request A ----\
Request B ----- &gt; Main Thread
Request C ----/
                    |
                    v
             Event Loop
                    |
                    v
              Send Responses
</code></pre>
]]></content:encoded></item><item><title><![CDATA[URL Parameters vs Query Strings in Express.js (Simple Explanation)]]></title><description><![CDATA[When we build APIs in Express.js, we often pass data in the URL.
But there are two common ways to pass data:

URL Parameters

Query Strings


At first, they look similar, but they are used for complet]]></description><link>https://newcohortblog2026.hashnode.dev/url-parameters-vs-query-strings-in-express-js-simple-explanation</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/url-parameters-vs-query-strings-in-express-js-simple-explanation</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Thu, 11 Jun 2026 16:01:16 GMT</pubDate><content:encoded><![CDATA[<p>When we build APIs in Express.js, we often pass data in the URL.</p>
<p>But there are <strong>two common ways</strong> to pass data:</p>
<ul>
<li><p>URL Parameters</p>
</li>
<li><p>Query Strings</p>
</li>
</ul>
<p>At first, they look similar, but they are used for completely different purposes.</p>
<p>Let’s understand them in a simple way.</p>
<h2>The Problem</h2>
<p>Imagine you are building a website like Instagram or an e-commerce app.</p>
<p>You need to:</p>
<ul>
<li><p>Show a <strong>user profile</strong></p>
</li>
<li><p>Search <strong>products</strong></p>
</li>
<li><p>Filter <strong>products by price or category</strong></p>
</li>
</ul>
<p>Now the question is:</p>
<p>How will the browser send this information to the server?</p>
<p>This is where <strong>URL Parameters</strong> and <strong>Query Strings</strong> come in.</p>
<h2>1. What are URL Parameters?</h2>
<p>URL parameters are used to identify a <strong>specific thing</strong>.</p>
<p>Think of it like:</p>
<blockquote>
<p>“Give me THIS exact user”</p>
</blockquote>
<h3>Example:</h3>
<pre><code class="language-plaintext">/users/101
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>101</code> is the user ID</p>
</li>
<li><p>It identifies a single user</p>
</li>
</ul>
<p>So URL params are like <strong>identity tags</strong></p>
<h3>Real-life meaning:</h3>
<ul>
<li><p>User profile page</p>
</li>
<li><p>Product detail page</p>
</li>
<li><p>Order details page</p>
</li>
</ul>
<p>You are asking for ONE specific resource</p>
<h3>In Express.js</h3>
<pre><code class="language-plaintext">app.get("/users/:id", (req, res) =&gt; {
  const userId = req.params.id;
  res.send(`User ID is ${userId}`);
});
</code></pre>
<h3>Accessing params:</h3>
<pre><code class="language-plaintext">req.params
</code></pre>
<h2>2. What are Query Strings?</h2>
<p>Query strings are used to <strong>filter or modify data</strong>.</p>
<p>Think of it like:</p>
<blockquote>
<p>“Give me users, but only filtered ones”</p>
</blockquote>
<h3>Example:</h3>
<pre><code class="language-plaintext">/users?role=admin&amp;age=25
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>role=admin</code> → filter</p>
</li>
<li><p><code>age=25</code> → filter condition</p>
</li>
</ul>
<p>So query strings are like <strong>search filters</strong></p>
<h3>Real-life meaning:</h3>
<ul>
<li><p>Search products</p>
</li>
<li><p>Filter by price</p>
</li>
<li><p>Sort data</p>
</li>
</ul>
<p>You are asking for MULTIPLE or filtered results</p>
<h3>In Express.js</h3>
<pre><code class="language-plaintext">app.get("/users", (req, res) =&gt; {
  const role = req.query.role;
  const age = req.query.age;

  res.send(`Role: \({role}, Age: \){age}`);
});
</code></pre>
<h3>Accessing query:</h3>
<pre><code class="language-plaintext">req.query
</code></pre>
<h2>3. Difference Between Params and Query Strings</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>URL Parameters</th>
<th>Query Strings</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Identify a resource</td>
<td>Filter or modify results</td>
</tr>
<tr>
<td>Data type</td>
<td>Fixed value</td>
<td>Optional values</td>
</tr>
<tr>
<td>Position</td>
<td><code>/users/101</code></td>
<td><code>/users?age=20</code></td>
</tr>
<tr>
<td>Express access</td>
<td><code>req.params</code></td>
<td><code>req.query</code></td>
</tr>
<tr>
<td>Example use</td>
<td>User profile</td>
<td>Search filters</td>
</tr>
</tbody></table>
<h2>4. When to Use What?</h2>
<h3>Use URL Params when:</h3>
<ul>
<li><p>You want a <strong>specific item</strong></p>
</li>
<li><p>Like user profile, product page</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-plaintext">/products/10
</code></pre>
<h3>Use Query Strings when:</h3>
<ul>
<li><p>You want to <strong>filter or search data</strong></p>
</li>
<li><p>Like sorting, filtering, pagination</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-plaintext">/products?category=mobile&amp;price=low
</code></pre>
<h2>Diagram Idea (Mental Picture)</h2>
<pre><code class="language-plaintext">/users/101
      ↑
   PARAM (identity)

-----------------------

/users?role=admin&amp;age=25
        ↑           ↑
      QUERY      QUERY (filters)
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Storing Uploaded Files and Serving Them in Express]]></title><description><![CDATA[Imagine you're building a social media application where users can upload profile pictures.
A user selects an image and clicks the Upload button.
The image successfully reaches your Express server.
No]]></description><link>https://newcohortblog2026.hashnode.dev/storing-uploaded-files-and-serving-them-in-express</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/storing-uploaded-files-and-serving-them-in-express</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Thu, 11 Jun 2026 05:43:38 GMT</pubDate><content:encoded><![CDATA[<p>Imagine you're building a social media application where users can upload profile pictures.</p>
<p>A user selects an image and clicks the Upload button.</p>
<p>The image successfully reaches your Express server.</p>
<p>Now a question arises:</p>
<p><strong>Where should this uploaded file be stored?</strong></p>
<p>And after storing it, <strong>how can other users view that image through a URL?</strong></p>
<p>This is where file storage and static file serving come into the picture.</p>
<p>In this article, we'll understand how Express stores uploaded files, how static files are served, and some important security practices</p>
<h2>The Problem</h2>
<p>Suppose a user uploads a file.</p>
<pre><code class="language-plaintext">User → Express Server → ?
</code></pre>
<p>The server receives the file, but where should it keep it?</p>
<p>If the server doesn't store the file anywhere, it will disappear after the request is completed.</p>
<p>So we need a place to save uploaded files and a way to access them later.</p>
<h3>Example of the Problem</h3>
<p>Let's say a user uploads:</p>
<pre><code class="language-plaintext">profile-picture.jpg
</code></pre>
<p>The server receives the file.</p>
<p>Without storage:</p>
<pre><code class="language-plaintext">User Uploads File
       ↓
Server Receives File
       ↓
   Request Ends
       ↓
   File Lost
</code></pre>
<p>We need permanent storage.</p>
<h2>1. Local Storage</h2>
<p>Files are stored inside the application's folder structure.</p>
<p>Example:</p>
<pre><code class="language-plaintext">project/
│
├── uploads/
│   ├── image1.jpg
│   ├── image2.png
│   └── document.pdf
│
├── server.js
└── package.json
</code></pre>
<p>When a user uploads a file, it is saved inside the <code>uploads</code> folder.</p>
<h3>Advantages</h3>
<ul>
<li><p>Easy to implement</p>
</li>
<li><p>Good for learning projects</p>
</li>
<li><p>No additional services required</p>
</li>
</ul>
<h3>Disadvantages</h3>
<ul>
<li><p>Limited storage</p>
</li>
<li><p>Files may be lost if the server crashes</p>
</li>
<li><p>Difficult to scale across multiple servers</p>
</li>
</ul>
<h2>2. External Storage</h2>
<p>Instead of storing files on the local machine, files are stored on cloud services.</p>
<p>Examples:</p>
<ul>
<li><p>Amazon Web Services S3</p>
</li>
<li><p>Cloudinary</p>
</li>
<li><p>Google Cloud Storage</p>
</li>
</ul>
<p>Flow:</p>
<pre><code class="language-plaintext">User
  ↓
Express Server
  ↓
Cloud Storage
</code></pre>
<h3>Advantages</h3>
<ul>
<li><p>Highly scalable</p>
</li>
<li><p>Better reliability</p>
</li>
<li><p>Easy file sharing</p>
</li>
</ul>
<h3>Disadvantages</h3>
<ul>
<li><p>Additional cost</p>
</li>
<li><p>More setup required</p>
</li>
</ul>
<h2>Upload Storage Folder Structure</h2>
<p>A common project structure looks like this:</p>
<pre><code class="language-plaintext">project/
│
├── uploads/
│   ├── profiles/
│   │   ├── user1.jpg
│   │   └── user2.jpg
│   │
│   ├── documents/
│   │   ├── resume.pdf
│   │   └── report.pdf
│
├── routes/
├── controllers/
├── server.js
└── package.json
</code></pre>
<p>Organizing files into folders makes management easier.</p>
<h2>Serving Static Files in Express</h2>
<h2>What is a Static File?</h2>
<p>A static file is a file that is sent directly to the browser without processing.</p>
<p>Examples:</p>
<ul>
<li><p>Images</p>
</li>
<li><p>Videos</p>
</li>
<li><p>CSS files</p>
</li>
<li><p>PDFs</p>
</li>
<li><p>JavaScript files</p>
</li>
</ul>
<p>Express provides middleware for serving static files.</p>
<pre><code class="language-plaintext">const express = require("express");

const app = express();

app.use("/uploads", express.static("uploads"));
</code></pre>
<p>This tells Express:</p>
<blockquote>
<p>"Whenever someone requests a file inside the uploads folder, serve it directly."</p>
</blockquote>
<h2>How Static File Serving Works</h2>
<p>Flow:</p>
<pre><code class="language-plaintext">Browser Requests Image
          ↓
      Express
          ↓
   uploads Folder
          ↓
     File Found
          ↓
     File Sent
</code></pre>
<h2>Accessing Uploaded Files via URL</h2>
<p>Suppose we have:</p>
<pre><code class="language-plaintext">uploads/profile.jpg
</code></pre>
<p>And Express configuration:</p>
<pre><code class="language-plaintext">app.use("/uploads", express.static("uploads"));
</code></pre>
<p>The file becomes accessible at:</p>
<pre><code class="language-plaintext">http://localhost:3000/uploads/profile.jpg
</code></pre>
<p>Browser request:</p>
<pre><code class="language-plaintext">GET /uploads/profile.jpg
</code></pre>
<p>Express:</p>
<pre><code class="language-plaintext">Looks inside uploads folder
         ↓
Finds profile.jpg
         ↓
Returns file
</code></pre>
<p>The browser displays the image.</p>
<h3>Complete Example</h3>
<pre><code class="language-plaintext">const express = require("express");

const app = express();

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

app.listen(3000, () =&gt; {
  console.log("Server running");
});
</code></pre>
<p>Folder structure:</p>
<pre><code class="language-plaintext">project/
│
├── uploads/
│   └── logo.png
│
└── server.js
</code></pre>
<p>URL:</p>
<pre><code class="language-plaintext">http://localhost:3000/uploads/logo.png
</code></pre>
<p>Result:</p>
<pre><code class="language-plaintext">Browser
   ↓
logo.png displayed
</code></pre>
<h3>Security Considerations for Uploads</h3>
<p><strong>File uploads can be dangerous if not handled properly.</strong></p>
<ol>
<li>Validate File Types</li>
</ol>
<p>Allow only specific file formats.</p>
<p>Example:</p>
<p>Allowed:</p>
<ul>
<li><p>jpg</p>
</li>
<li><p>png</p>
</li>
<li><p>pdf</p>
</li>
</ul>
<p>Blocked:</p>
<ul>
<li><p>exe</p>
</li>
<li><p>bat</p>
</li>
<li><p>sh</p>
</li>
</ul>
<h3>2. Limit File Size</h3>
<p>Prevent users from uploading huge files.</p>
<p>Example:</p>
<pre><code class="language-plaintext">Maximum Size: 5 MB
</code></pre>
<p>This protects server resources.</p>
<h3>3. Rename Uploaded Files</h3>
<p>Avoid storing original filenames.</p>
<p>Bad:</p>
<pre><code class="language-plaintext">resume.pdf
</code></pre>
<p>Good:</p>
<pre><code class="language-plaintext">17123456789.pdf
</code></pre>
<p>Unique names prevent conflicts.</p>
<h3>4. Store Uploads Outside Sensitive Directories</h3>
<p><strong>Never allow uploads inside source code folders.</strong></p>
<p>Bad:</p>
<pre><code class="language-plaintext">src/
 └── uploads/
</code></pre>
<p>Better:</p>
<pre><code class="language-plaintext">uploads/
</code></pre>
<h3>5. Scan Files if Possible</h3>
<p>For production applications, scan uploaded files for malware before making them available.</p>
<h3>6. Restrict Access</h3>
<p>Not every uploaded file should be publicly accessible.</p>
<p>Examples:</p>
<ul>
<li><p>Public profile pictures → Public URLs</p>
</li>
<li><p>User documents → Authenticated access only</p>
</li>
</ul>
<h2>Real-World Flow</h2>
<pre><code class="language-plaintext">User Uploads Image
          ↓
Express Receives File
          ↓
Validation
(File Type + Size)
          ↓
Store File
(Local Storage / Cloud Storage)
          ↓
Save File Path in Database
          ↓
Generate URL
          ↓
Browser Accesses URL
          ↓
Express Serves File
</code></pre>
]]></content:encoded></item><item><title><![CDATA[The new Keyword in JavaScript: How Objects Are Created Behind the Scenes
]]></title><description><![CDATA[Introduction
When learning JavaScript, you'll often see code like this:
function User(name) {
  this.name = name;
}

const user1 = new User("Ashish");

Many beginners use the new keyword without under]]></description><link>https://newcohortblog2026.hashnode.dev/the-new-keyword-in-javascript-how-objects-are-created-behind-the-scenes</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/the-new-keyword-in-javascript-how-objects-are-created-behind-the-scenes</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Wed, 10 Jun 2026 08:00:34 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>When learning JavaScript, you'll often see code like this:</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}

const user1 = new User("Ashish");
</code></pre>
<p>Many beginners use the <code>new</code> keyword without understanding what it actually does.</p>
<p>Questions like these are common:</p>
<ul>
<li><p>What does <code>new</code> do?</p>
</li>
<li><p>Why do we use it before a function?</p>
</li>
<li><p>How is an object created?</p>
</li>
<li><p>What is the connection between constructors and prototypes?</p>
</li>
</ul>
<p>In this article, we'll understand the <code>new</code> keyword step by step with simple examples.</p>
<h2>The Problem</h2>
<p>Imagine you want to create multiple users in your application.</p>
<p>Without a constructor function, you would have to create every object manually.</p>
<pre><code class="language-plaintext">const user1 = {
  name: "Ashish",
  greet() {
    console.log("Hello");
  }
};

const user2 = {
  name: "Rahul",
  greet() {
    console.log("Hello");
  }
};
</code></pre>
<p>Notice the problem?</p>
<p>We are repeating the same structure again and again.</p>
<p>For a few objects this is fine, but for hundreds or thousands of objects it becomes difficult to maintain.</p>
<p>We need a way to create objects from a blueprint.</p>
<p>That's where constructor functions and the <code>new</code> keyword come in.</p>
<h2>What is the <code>new</code> Keyword?</h2>
<p>The <code>new</code> keyword is used to create an object from a constructor function.</p>
<p>It automatically creates a new object and connects it with the constructor.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}

const user1 = new User("Ashish");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">{ name: "Ashish" }
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">new User("Ashish")
</code></pre>
<p>creates a new object and assigns <code>"Ashish"</code> to its <code>name</code> property.</p>
<h2>What is a Constructor Function?</h2>
<p>A constructor function is a normal function that is intended to create objects.</p>
<p>By convention, constructor function names start with a capital letter.</p>
<pre><code class="language-plaintext">function User(name, age) {
  this.name = name;
  this.age = age;
}
</code></pre>
<p>Creating objects:</p>
<pre><code class="language-plaintext">const user1 = new User("Ashish", 25);
const user2 = new User("Rahul", 22);

console.log(user1);
console.log(user2);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">User { name: "Ashish", age: 25 }

User { name: "Rahul", age: 22 }
</code></pre>
<p>The constructor acts as a blueprint.</p>
<h3>What Happens When We Use <code>new</code>?</h3>
<p>Many developers think <code>new</code> is magic.</p>
<p>Actually, JavaScript performs four important steps.</p>
<p>Let's understand them one by one.</p>
<h3>Step 1: Create an Empty Object</h3>
<p>When JavaScript sees:</p>
<pre><code class="language-plaintext">new User("Ashish")
</code></pre>
<p>it first creates an empty object.</p>
<pre><code class="language-plaintext">{}
</code></pre>
<h3>Step 2: Link the Object to the Prototype</h3>
<p>The newly created object gets connected to the constructor's prototype.</p>
<p>Conceptually:</p>
<pre><code class="language-plaintext">obj.__proto__ = User.prototype;
</code></pre>
<p>This allows the object to access shared methods later.</p>
<h3>Step 3: Bind <code>this</code> to the New Object</h3>
<p>Inside the constructor:</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}
</code></pre>
<p><code>this</code> now refers to the newly created object.</p>
<p>So JavaScript executes:</p>
<pre><code class="language-plaintext">obj.name = "Ashish";
</code></pre>
<p>Result:</p>
<pre><code class="language-plaintext">{
  name: "Ashish"
}
</code></pre>
<h3>Step 4: Return the Object</h3>
<p>Finally, JavaScript automatically returns the created object.</p>
<p>Equivalent behavior:</p>
<pre><code class="language-plaintext">return obj;
</code></pre>
<p>So:</p>
<pre><code class="language-plaintext">const user1 = new User("Ashish");
</code></pre>
<p>becomes:</p>
<pre><code class="language-plaintext">{
  name: "Ashish"
}
</code></pre>
<h3>Behind the Scenes</h3>
<p>The code:</p>
<pre><code class="language-plaintext">const user1 = new User("Ashish");
</code></pre>
<p>works roughly like this:</p>
<pre><code class="language-plaintext">const obj = {};

obj.__proto__ = User.prototype;

User.call(obj, "Ashish");

return obj;
</code></pre>
<p>This is essentially what the <code>new</code> keyword does internally.</p>
<h2>Adding Methods Using Prototype</h2>
<p>Suppose we add a method directly inside the constructor.</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;

  this.greet = function () {
    console.log("Hello");
  };
}
</code></pre>
<p>Every object gets its own copy of <code>greet</code>.</p>
<p>This wastes memory.</p>
<p>A better approach is using the prototype.</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}

User.prototype.greet = function () {
  console.log(`Hello, ${this.name}`);
};
</code></pre>
<p>Now all objects share the same method.</p>
<pre><code class="language-plaintext">const user1 = new User("Ashish");
const user2 = new User("Rahul");
</code></pre>
<pre><code class="language-plaintext">user1.greet();
user2.greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello, Ashish
Hello, Rahul
</code></pre>
<h2>How <code>new</code> Links Prototypes</h2>
<p>Let's check it.</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}

const user1 = new User("Ashish");

console.log(
  Object.getPrototypeOf(user1) === User.prototype
);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<p>This proves that the object is connected to the constructor's prototype.</p>
<p>Because of this connection:</p>
<pre><code class="language-plaintext">user1.greet()
</code></pre>
<p>can access methods stored on:</p>
<pre><code class="language-plaintext">User.prototype
</code></pre>
<h2>Checking the Constructor</h2>
<p>Every created object remembers which constructor created it.</p>
<pre><code class="language-plaintext">function User(name) {
  this.name = name;
}

const user1 = new User("Ashish");

console.log(user1.constructor);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">[Function: User]
</code></pre>
<p>This indicates that the object was created using the <code>User</code> constructor.</p>
<h1>Constructor → Instance Creation Flow</h1>
<pre><code class="language-plaintext">Constructor Function

        │
        
       new

        │

 Creates Empty Object

        │
   Links Prototype

        │

     Binds this

        │

   Returns Object

        │

     Instance
</code></pre>
<h1>Prototype Linking Flow</h1>
<pre><code class="language-plaintext">User Constructor
       │

User.prototype
       │

   __proto__
       │
       
     user1
</code></pre>
<p>Because of this link:</p>
<pre><code class="language-plaintext">user1.greet()
</code></pre>
<p>can access methods from:</p>
<pre><code class="language-plaintext">User.prototype
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Callbacks in JavaScript: Why They Exist]]></title><description><![CDATA[Introduction
Imagine you order a pizza online.
You don't stand outside the restaurant and watch the chef make your pizza. Instead, you place the order and continue doing other things. When the pizza i]]></description><link>https://newcohortblog2026.hashnode.dev/callbacks-in-javascript-why-they-exist</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/callbacks-in-javascript-why-they-exist</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Wed, 10 Jun 2026 07:42:41 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Imagine you order a pizza online.</p>
<p>You don't stand outside the restaurant and watch the chef make your pizza. Instead, you place the order and continue doing other things. When the pizza is ready, the delivery person calls you.</p>
<p>This "call me when you're done" idea is exactly how callbacks work in JavaScript.</p>
<p>Callbacks allow JavaScript to continue doing other work while waiting for a task to finish. When the task is completed, JavaScript calls a function that you provided earlier.</p>
<p>In this article, we'll understand what callback functions are, why they exist, how they are used in asynchronous programming, and the problems they can create.</p>
<h2>Functions Are Values in JavaScript</h2>
<p>Before understanding callbacks, we need to understand an important feature of JavaScript.</p>
<p>In JavaScript, functions are treated like values.</p>
<p>This means a function can:</p>
<ul>
<li><p>Be stored in a variable</p>
</li>
<li><p>Be passed as an argument</p>
</li>
<li><p>Be returned from another function</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-plaintext">function sayHello() {
  console.log("Hello");
}

const greet = sayHello;

greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello
</code></pre>
<p>Here, the function is assigned to another variable and then executed.</p>
<p>Because functions can be passed around like values, callbacks become possible.</p>
<h2>What Is a Callback Function?</h2>
<p>A callback function is simply a function passed into another function as an argument.</p>
<p>The receiving function can execute it whenever needed.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function greet(name, callback) {
  console.log("Hello " + name);

  callback();
}

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

greet("Ashish", sayBye);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Ashish
Goodbye!
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>sayBye</code> is passed as an argument.</p>
</li>
<li><p><code>greet</code> receives it.</p>
</li>
<li><p><code>greet</code> executes it later.</p>
</li>
</ul>
<p>Therefore, <code>sayBye</code> is called a callback function.</p>
<h2>Why Do Callbacks Exist?</h2>
<p>Let's understand the problem first.</p>
<p>Imagine JavaScript is downloading data from a server.</p>
<p>This operation may take several seconds.</p>
<p>If JavaScript waits for the server response before doing anything else, the application will freeze.</p>
<p>That would create a poor user experience.</p>
<p>JavaScript solves this problem using asynchronous programming.</p>
<p>Instead of waiting:</p>
<ol>
<li><p>Start the task.</p>
</li>
<li><p>Continue doing other work.</p>
</li>
<li><p>Execute a callback when the task finishes.</p>
</li>
</ol>
<h3>Simple Real-Life Example</h3>
<p>Suppose you ask your friend to wash your bike.</p>
<p>Instead of standing beside them and waiting, you say:</p>
<blockquote>
<p>"Call me when you're done."</p>
</blockquote>
<p>That "call me later" instruction is the callback.</p>
<p>Flow:</p>
<pre><code class="language-plaintext">Start bike washing
      |
      v
Do other work
      |
      v
Bike washing completed
      |
      v
Callback executes
</code></pre>
<p>The same concept is used in JavaScript.</p>
<h2>Callback Example in Asynchronous Programming</h2>
<p>Consider a timer.</p>
<pre><code class="language-plaintext">console.log("Start");

setTimeout(function () {
  console.log("Task Finished");
}, 2000);

console.log("End");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Start
End
Task Finished
</code></pre>
<p>Why?</p>
<ul>
<li><p>JavaScript starts the timer.</p>
</li>
<li><p>It doesn't wait for 2 seconds.</p>
</li>
<li><p>It continues executing the next line.</p>
</li>
<li><p>After 2 seconds, the callback function runs.</p>
</li>
</ul>
<p>The function inside <code>setTimeout</code> is a callback.</p>
<h2>Passing Functions as Arguments</h2>
<p>Callbacks work because functions can be passed as arguments.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function performOperation(a, b, operation) {
  return operation(a, b);
}

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

const result = performOperation(10, 20, add);

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">30
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>add</code> is passed as an argument.</p>
</li>
<li><p><code>performOperation</code> executes it.</p>
</li>
<li><p><code>add</code> acts as a callback.</p>
</li>
</ul>
<h2>Common Callback Use Cases</h2>
<p>Callbacks are used in many places.</p>
<h2>1. Timers</h2>
<pre><code class="language-plaintext">setTimeout(() =&gt; {
  console.log("Executed later");
}, 1000);
</code></pre>
<h2>2. Event Handling</h2>
<pre><code class="language-plaintext">button.addEventListener("click", function () {
  console.log("Button clicked");
});
</code></pre>
<p>When the user clicks the button, the callback executes.</p>
<h2>3. Array Methods</h2>
<pre><code class="language-plaintext">const numbers = [1, 2, 3];

numbers.forEach(function (num) {
  console.log(num);
});
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">1
2
3
</code></pre>
<p>The function passed to <code>forEach</code> is a callback.</p>
<h2>4. API Calls (Older Style)</h2>
<pre><code class="language-plaintext">fetchData(function (data) {
  console.log(data);
});
</code></pre>
<p>After data arrives, the callback runs.</p>
]]></content:encoded></item><item><title><![CDATA[Sessions vs JWT vs Cookies: Understanding Authentication Approaches]]></title><description><![CDATA[Introduction
Imagine you are using an online shopping website.
You log in once, browse products, add items to your cart, and move between different pages without logging in again and again.
Have you e]]></description><link>https://newcohortblog2026.hashnode.dev/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/sessions-vs-jwt-vs-cookies-understanding-authentication-approaches</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Wed, 10 Jun 2026 07:33:27 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Imagine you are using an online shopping website.</p>
<p>You log in once, browse products, add items to your cart, and move between different pages without logging in again and again.</p>
<p>Have you ever wondered how the website remembers that you are already logged in?</p>
<p>This is where <strong>Sessions</strong>, <strong>Cookies</strong>, and <strong>JWT (JSON Web Tokens)</strong> come into the picture.</p>
<p>These are the most common authentication approaches used in modern web applications. Understanding them is important for every backend developer because almost every application needs a way to identify users after login.</p>
<p>In this article, we'll understand:</p>
<ul>
<li><p>What Sessions are</p>
</li>
<li><p>What Cookies are</p>
</li>
<li><p>What JWT Tokens are</p>
</li>
<li><p>Stateful vs Stateless Authentication</p>
</li>
<li><p>Session-based Authentication vs JWT Authentication</p>
</li>
<li><p>When to use each approach</p>
</li>
</ul>
<h2>What Are Cookies?</h2>
<p>A Cookie is a small piece of data stored in the user's browser.</p>
<p>When the browser sends future requests to the server, it automatically includes the cookie.</p>
<h3>Example</h3>
<p>After login, the server sends:</p>
<pre><code class="language-plaintext">Set-Cookie: userId=123
</code></pre>
<p>Browser stores it.</p>
<p>Future requests:</p>
<pre><code class="language-plaintext">Cookie: userId=123
</code></pre>
<p>Now the server can identify the user.</p>
<h2>Cookie Flow</h2>
<pre><code class="language-plaintext">User Login
     |
     v
Server Creates Cookie
     |
     v
Browser Stores Cookie
     |
     v
Future Requests Include Cookie
</code></pre>
<h2>What Are Sessions?</h2>
<p>A Session is a server-side storage mechanism used to keep track of logged-in users.</p>
<p>Instead of storing user information directly in the browser, the server stores it in memory or a database.</p>
<p>The browser only receives a Session ID.</p>
<h3>Example</h3>
<p>User logs in:</p>
<pre><code class="language-plaintext">Session ID = abc123
</code></pre>
<p>Server stores:</p>
<pre><code class="language-plaintext">{
  "abc123": {
    "userId": 101,
    "username": "ashish"
  }
}
</code></pre>
<p>Browser stores only:</p>
<pre><code class="language-plaintext">sessionId=abc123
</code></pre>
<p>When the user sends another request:</p>
<ol>
<li><p>Browser sends Session ID.</p>
</li>
<li><p>Server finds matching session data.</p>
</li>
<li><p>User is authenticated.</p>
</li>
</ol>
<h2>Session Authentication Flow</h2>
<pre><code class="language-plaintext">User Login
     |
     v
Server Creates Session
     |
     v
Server Stores User Data
     |
     v
Session ID Sent To Browser
     |
     v
Browser Sends Session ID
     |
     v
Server Verifies Session
</code></pre>
<h2>What Is JWT (JSON Web Token)?</h2>
<p>JWT is a self-contained token that stores user information inside the token itself.</p>
<p>Unlike sessions, the server does not need to store user data separately.</p>
<p>After login:</p>
<pre><code class="language-plaintext">eyJhbGciOi...
</code></pre>
<p>The token contains encoded information such as:</p>
<pre><code class="language-plaintext">{
  "userId": 101,
  "name": "Ashish",
  "role": "user"
}
</code></pre>
<p>The browser stores this token and sends it with every request.</p>
<h2>JWT Authentication Flow</h2>
<pre><code class="language-plaintext">User Login
     |
     v
Server Creates JWT
     |
     v
JWT Sent To Browser
     |
     v
Browser Stores JWT
     |
     v
JWT Sent With Requests
     |
     v
Server Verifies Signature
</code></pre>
<h2>Stateful vs Stateless Authentication</h2>
<h2>Stateful Authentication</h2>
<p>The server stores user information.</p>
<p>Examples:</p>
<ul>
<li><p>Sessions</p>
</li>
<li><p>Session-based authentication</p>
</li>
</ul>
<p>The server must remember every logged-in user.</p>
<h3>Characteristics</h3>
<ul>
<li><p>Server stores user state.</p>
</li>
<li><p>Requires session storage.</p>
</li>
<li><p>Easy logout implementation.</p>
</li>
<li><p>More server memory usage.</p>
</li>
</ul>
<h2>Stateless Authentication</h2>
<p>The server stores nothing about logged-in users.</p>
<p>Examples:</p>
<ul>
<li>JWT Authentication</li>
</ul>
<p>All required information exists inside the token.</p>
<h3>Characteristics</h3>
<ul>
<li><p>No session storage required.</p>
</li>
<li><p>Easier horizontal scaling.</p>
</li>
<li><p>Less server memory usage.</p>
</li>
<li><p>Token management becomes important.</p>
</li>
</ul>
<h2>Session-Based Authentication vs JWT Authentication</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Session Authentication</th>
<th>JWT Authentication</th>
</tr>
</thead>
<tbody><tr>
<td>Storage</td>
<td>Server stores user data</td>
<td>Token stores user data</td>
</tr>
<tr>
<td>Type</td>
<td>Stateful</td>
<td>Stateless</td>
</tr>
<tr>
<td>Server Memory</td>
<td>Required</td>
<td>Not Required</td>
</tr>
<tr>
<td>Scalability</td>
<td>Moderate</td>
<td>High</td>
</tr>
<tr>
<td>Logout Handling</td>
<td>Easy</td>
<td>Slightly More Complex</td>
</tr>
<tr>
<td>Microservices Support</td>
<td>Less Suitable</td>
<td>Highly Suitable</td>
</tr>
<tr>
<td>Performance</td>
<td>Additional session lookup</td>
<td>Token verification only</td>
</tr>
<tr>
<td>Common Usage</td>
<td>Traditional web apps</td>
<td>APIs and modern applications</td>
</tr>
</tbody></table>
<h2>Real-World Examples</h2>
<h3>Session-Based Authentication</h3>
<p>Commonly used in:</p>
<ul>
<li><p>Banking websites</p>
</li>
<li><p>Admin dashboards</p>
</li>
<li><p>Traditional server-rendered applications</p>
</li>
<li><p>Enterprise applications</p>
</li>
</ul>
<p>Reason:</p>
<p>The server has full control over user sessions.'</p>
<h3>JWT Authentication</h3>
<p>Commonly used in:</p>
<ul>
<li><p>REST APIs</p>
</li>
<li><p>Mobile applications</p>
</li>
<li><p>React applications</p>
</li>
<li><p>Next.js applications</p>
</li>
<li><p>Microservices architecture</p>
</li>
</ul>
<p>Reason:</p>
<p>No server-side session storage is required.</p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript: Write Strings the Modern Way]]></title><description><![CDATA[Introduction
Strings are one of the most commonly used data types in JavaScript. We use them to display messages, create dynamic content, build URLs, and much more.
Before ES6 (ECMAScript 2015), devel]]></description><link>https://newcohortblog2026.hashnode.dev/template-literals-in-javascript-write-strings-the-modern-way</link><guid isPermaLink="true">https://newcohortblog2026.hashnode.dev/template-literals-in-javascript-write-strings-the-modern-way</guid><dc:creator><![CDATA[Avinash Powar]]></dc:creator><pubDate>Wed, 10 Jun 2026 07:21:38 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Strings are one of the most commonly used data types in JavaScript. We use them to display messages, create dynamic content, build URLs, and much more.</p>
<p>Before ES6 (ECMAScript 2015), developers used string concatenation with the <code>+</code> operator to combine strings and variables. While it worked, it often made code difficult to read and maintain.</p>
<p>To solve this problem, JavaScript introduced <strong>Template Literals</strong>, a modern and cleaner way to work with strings.</p>
<h2>The Problem with Traditional String Concatenation</h2>
<p>Before template literals, strings were combined using the <code>+</code> operator.</p>
<h3>Example</h3>
<pre><code class="language-plaintext">const name = "Ashish";
const age = 24;

const message = "My name is " + name + " and I am " + age + " years old.";

console.log(message);
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">My name is Ashish and I am 24 years old.
</code></pre>
<p>Although this works, the code becomes harder to read when many variables are involved.</p>
<h3>Another Example</h3>
<pre><code class="language-plaintext">const product = "Laptop";
const price = 50000;

const text =
  "The product name is " +
  product +
  " and its price is ₹" +
  price +
  ".";

console.log(text);
</code></pre>
<p>This looks messy and is difficult to maintain.</p>
<h2>What are Template Literals?</h2>
<p>Template literals are a modern way to create strings in JavaScript.</p>
<p>Instead of using single quotes (' ') or double quotes (" "), template literals use backticks ( `).</p>
<p>Syntax <code>Text goes here</code></p>
<p>Example:</p>
<p>const message = <code>Hello JavaScript</code>;</p>
<p>console.log(message);</p>
<h2>Embedding Variables in Strings</h2>
<p>One of the biggest advantages of template literals is <strong>string interpolation</strong>.</p>
<p>We can insert variables directly inside a string using:</p>
<pre><code class="language-plaintext">${variableName}
</code></pre>
<h3>Example</h3>
<pre><code class="language-plaintext">const name = "Ashish";
const age = 24;

const message = `My name is \({name} and I am \){age} years old.`;

console.log(message);
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">My name is Ashish and I am 24 years old.
</code></pre>
<p>The code is much cleaner and easier to understand.</p>
<h2>Before vs After Template Literals</h2>
<h3>Traditional Concatenation</h3>
<pre><code class="language-plaintext">const city = "Pune";

console.log("I live in " + city + ".");
</code></pre>
<h3>Template Literal</h3>
<pre><code class="language-plaintext">const city = "Pune";

console.log(`I live in ${city}.`);
</code></pre>
<p>The second approach is shorter and more readable.</p>
<h2>Multi-Line Strings</h2>
<p>Creating multi-line strings was difficult before template literals.</p>
<h3>Old Way</h3>
<pre><code class="language-plaintext">const text =
  "JavaScript is powerful.\n" +
  "JavaScript is flexible.\n" +
  "JavaScript is popular.";

console.log(text);
</code></pre>
<h3>Using Template Literals</h3>
<pre><code class="language-plaintext">const text = `
JavaScript is powerful.
JavaScript is flexible.
JavaScript is popular.
`;

console.log(text);
</code></pre>
<p>Template literals preserve line breaks automatically.</p>
<h2>Expressions Inside Template Literals</h2>
<p>We can even execute JavaScript expressions inside ${}.</p>
<h3>Example</h3>
<pre><code class="language-plaintext">const a = 10;
const b = 20;

console.log(`The sum is ${a + b}`);
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">The sum is 30
</code></pre>
<p><strong>Another example:</strong></p>
<pre><code class="language-plaintext">const price = 1000;
const discount = 200;

console.log(`Final Price: ₹${price - discount}`);
</code></pre>
<h3>Output</h3>
<pre><code class="language-plaintext">Final Price: ₹800
</code></pre>
]]></content:encoded></item></channel></rss>