<?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[PortfolioHub Blog]]></title><description><![CDATA[PortfolioHub Blog]]></description><link>https://blog.portfoliohub.in</link><image><url>https://cdn.hashnode.com/uploads/logos/6951f0fa71561c01e2f304ee/0ed3dbb3-27ba-4339-9f5e-25dbad520bbe.webp</url><title>PortfolioHub Blog</title><link>https://blog.portfoliohub.in</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 20 Apr 2026 15:35:00 GMT</lastBuildDate><atom:link href="https://blog.portfoliohub.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Sessions vs JWT vs Cookies]]></title><description><![CDATA[If you're confused about the differences between sessions, JWT, and cookies - you're not alone. These terms are often mixed up, and many developers struggle to understand how they relate.
Here's the t]]></description><link>https://blog.portfoliohub.in/sessions-vs-jwt-vs-cookies</link><guid isPermaLink="true">https://blog.portfoliohub.in/sessions-vs-jwt-vs-cookies</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Mon, 20 Apr 2026 03:04:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/7481f07d-1143-4df0-8b72-bfbe916cf2e1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're confused about the differences between sessions, JWT, and cookies - you're not alone. These terms are often mixed up, and many developers struggle to understand how they relate.</p>
<p>Here's the truth: <strong>Cookies are a storage mechanism. Sessions and JWT are authentication strategies. They often work together.</strong></p>
<p>Let me clear up the confusion once and for all.<br /><strong>First, Understand the Difference</strong></p>
<table>
<thead>
<tr>
<th><strong>Term</strong></th>
<th><strong>What it is</strong></th>
<th><strong>Analogy</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Cookie</strong></td>
<td>A storage mechanism (client-side)</td>
<td>A wallet you carry</td>
</tr>
<tr>
<td><strong>Session</strong></td>
<td>Server-side authentication state</td>
<td>A VIP card checked against a list at the door</td>
</tr>
<tr>
<td><strong>JWT</strong></td>
<td>Self-contained token</td>
<td>A passport with all your info embedded</td>
</tr>
</tbody></table>
<p><strong>Key insight:</strong> You can store a session ID in a cookie. You can also store a JWT in a cookie. Cookies are just the delivery method.</p>
<p><strong>What are Cookies?</strong><br />Cookies are small pieces of data (max 4KB) that browsers store and automatically send with every request to the same domain.</p>
<p><strong>How Cookies Work?</strong></p>
<ol>
<li><p>Server sets cookie via response header: Set-Cookie: userId=123; HttpOnly; Secure; Max-Age=3600</p>
</li>
<li><p>Browser stores the cookie</p>
</li>
<li><p>Browser automatically sends cookie with every subsequent request: Cookie: userId=123</p>
</li>
</ol>
<h3><strong>Cookie Attributes (Important!)</strong></h3>
<pre><code class="language-javascript">res.cookie("token", "abc123", {
  httpOnly: true,   // Can't be accessed by JavaScript (prevents XSS)
  secure: true,     // Only sent over HTTPS
  sameSite: "strict", // Protects against CSRF
  maxAge: 3600000,  // 1 hour expiration
  domain: ".example.com" // Available to subdomains
});
</code></pre>
<h3><strong>What Cookies Are NOT</strong></h3>
<ul>
<li><p><strong>Not secure by default</strong> - They need proper flags (HttpOnly, Secure, SameSite)</p>
</li>
<li><p><strong>Not for large data</strong> - 4KB limit</p>
</li>
<li><p><strong>Not cross-domain</strong> - They belong to specific domains</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/6936b05a-50e8-4d6d-b1f4-ce8a9ba53d02.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>How Session Authentication Works</strong></h3>
<ol>
<li><p>Client sends login credentials to server<br />└─ POST /login with username + password</p>
</li>
<li><p>Server verifies credentials against database<br />└─ If valid, creates a unique session ID</p>
</li>
<li><p>Server stores session data (in memory/Redis/DB)<br />└─ Example: { userId: 123, role: "admin", expires: "2024-01-01" }</p>
</li>
<li><p>Server sends session ID to client via cookie<br />└─ Set-Cookie: sessionId=abc123; HttpOnly; Secure</p>
</li>
<li><p>Browser stores cookie automatically</p>
</li>
<li><p>Client includes cookie in all subsequent requests<br />└─ Cookie: sessionId=abc123</p>
</li>
<li><p>Server reads cookie, looks up session data<br />└─ Finds userId, role, etc. from session store</p>
</li>
<li><p>Server responds with requested data<br />└─ No need to re-authenticate for each request</p>
</li>
<li><p>On logout, server destroys session<br />└─ Client cookie becomes invalid</p>
</li>
</ol>
<h3><strong>Session Code Example</strong></h3>
<pre><code class="language-javascript">import express from "express";
import session from "express-session";
import MongoStore from "connect-mongo";

const app = express();

// Session configuration
app.use(session({
  secret: "your-secret-key",
  resave: false,
  saveUninitialized: false,
  store: MongoStore.create({
    mongoUrl: "mongodb://localhost:27017/sessions"
  }),
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    maxAge: 1000 * 60 * 60 * 24 // 24 hours
  }
}));

// Login route
app.post("/login", async (req, res) =&gt; {
  const { username, password } = req.body;
  
  // Verify user (check database)
  const user = await User.findOne({ username });
  
  if (user &amp;&amp; await bcrypt.compare(password, user.password)) {
    // Store user info in session
    req.session.userId = user._id;
    req.session.username = user.username;
    req.session.role = user.role;
    
    res.json({ message: "Logged in successfully" });
  } else {
    res.status(401).json({ error: "Invalid credentials" });
  }
});

// Protected route
app.get("/profile", (req, res) =&gt; {
  // Check if session exists
  if (!req.session.userId) {
    return res.status(401).json({ error: "Not authenticated" });
  }
  
  res.json({
    userId: req.session.userId,
    username: req.session.username
  });
});

// Logout
app.post("/logout", (req, res) =&gt; {
  req.session.destroy((err) =&gt; {
    if (err) {
      return res.status(500).json({ error: "Logout failed" });
    }
    res.clearCookie("connect.sid");
    res.json({ message: "Logged out" });
  });
});
</code></pre>
<h3><strong>Session Storage Options</strong></h3>
<table>
<thead>
<tr>
<th><strong>Storage</strong></th>
<th><strong>Use Case</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Memory (default)</td>
<td>Development only (doesn't scale)</td>
</tr>
<tr>
<td>Redis</td>
<td>High performance, production</td>
</tr>
<tr>
<td>MongoDB</td>
<td>Good for smaller apps</td>
</tr>
<tr>
<td>PostgreSQL</td>
<td>If already using Postgres</td>
</tr>
</tbody></table>
<h3><strong>Pros &amp; Cons of Sessions</strong></h3>
<table>
<thead>
<tr>
<th><strong>Pros</strong></th>
<th><strong>Cons</strong></th>
</tr>
</thead>
<tbody><tr>
<td>✅ Simple to implement</td>
<td>❌ Server needs to store sessions</td>
</tr>
<tr>
<td>✅ Easy to invalidate</td>
<td>❌ Doesn't scale horizontally easily</td>
</tr>
<tr>
<td>✅ Small client payload</td>
<td>❌ Requires shared session store</td>
</tr>
<tr>
<td>✅ Built-in CSRF protection (with SameSite)</td>
<td>❌ Can be slower (database lookup)</td>
</tr>
</tbody></table>
<h2><strong>What is JWT (JSON Web Token)?</strong></h2>
<p>JWT is a <strong>stateless</strong> authentication mechanism. The token contains all necessary user information, signed by the server. No server-side storage required.</p>
<h3><strong>JWT Structure</strong></h3>
<p>A JWT looks like this:</p>
<pre><code class="language-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjMiLCJyb2xlIjoidXNlciIsImlhdCI6MTY5MDAwMDAwMCwiZXhwIjoxNjkwMDAzNjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
</code></pre>
<h3><strong>Pros &amp; Cons of JWT</strong></h3>
<table>
<thead>
<tr>
<th><strong>Pros</strong></th>
<th><strong>Cons</strong></th>
</tr>
</thead>
<tbody><tr>
<td>✅ Stateless (scales easily)</td>
<td>❌ Can't invalidate easily (until expiry)</td>
</tr>
<tr>
<td>✅ No database lookup needed</td>
<td>❌ Larger payload size</td>
</tr>
<tr>
<td>✅ Works across domains (CORS)</td>
<td>❌ Security depends on secret management</td>
</tr>
<tr>
<td>✅ Mobile-friendly</td>
<td>❌ Token theft is harder to revoke</td>
</tr>
</tbody></table>
<hr />
<h2><strong>Head-to-Head Comparison</strong></h2>
<h3><strong>Sessions vs JWT</strong></h3>
<table>
<thead>
<tr>
<th><strong>Aspect</strong></th>
<th><strong>Sessions</strong></th>
<th><strong>JWT</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>State</strong></td>
<td>Server-side state</td>
<td>Stateless</td>
</tr>
<tr>
<td><strong>Storage</strong></td>
<td>Server (DB/Redis)</td>
<td>Client</td>
</tr>
<tr>
<td><strong>Scalability</strong></td>
<td>Needs shared session store</td>
<td>Horizontally scalable</td>
</tr>
<tr>
<td><strong>Invalidation</strong></td>
<td>Instant (delete session)</td>
<td>Until expiry (or use blacklist)</td>
</tr>
<tr>
<td><strong>Payload Size</strong></td>
<td>Small (session ID)</td>
<td>Larger (all user data)</td>
</tr>
<tr>
<td><strong>Performance</strong></td>
<td>Database lookup each request</td>
<td>Verify signature (fast)</td>
</tr>
<tr>
<td><strong>Logout</strong></td>
<td>Simple (destroy session)</td>
<td>Complex (must clear client token)</td>
</tr>
<tr>
<td><strong>CSRF Protection</strong></td>
<td>Built-in (with SameSite)</td>
<td>Must implement manually</td>
</tr>
</tbody></table>
<h3><strong>When to Use Sessions</strong></h3>
<pre><code class="language-javascript">// ✅ GOOD USE CASES FOR SESSIONS

// 1. Traditional web apps (server-rendered)
app.get("/dashboard", (req, res) =&gt; {
  if (req.session.userId) {
    res.render("dashboard", { user: req.session.user });
  }
});

// 2. When you need instant logout/revocation
app.post("/admin/block-user", (req, res) =&gt; {
  sessionStore.destroy(userSessionId); // Immediately blocks access
});

// 3. When storing large amounts of user data
req.session.userPreferences = { theme: "dark", language: "es" }; // Not in cookie

// 4. Banking/financial apps (higher security requirements)
</code></pre>
<h3><strong>When to Use JWT</strong></h3>
<pre><code class="language-javascript">// ✅ GOOD USE CASES FOR JWT

// 1. REST APIs (stateless)
app.get("/api/users", authenticateToken, (req, res) =&gt; {
  // No session lookup needed
});

// 2. Microservices architecture
Service A: Generate token with user info
Service B: Verify token without calling auth service

// 3. Mobile applications
// Tokens work well with mobile's lack of cookie support

// 4. Single Page Applications (SPA)
// Works with localStorage or cookies

// 5. Third-party API access
const apiToken = jwt.sign({ clientId: "abc123" }, SECRET);
</code></pre>
<h3><strong>When to Use Both Together</strong></h3>
<p>Many production apps combine both:</p>
<p>javascript</p>
<pre><code class="language-plaintext">// Hybrid approach: JWT stored in HTTP-only cookie
app.post("/login", async (req, res) =&gt; {
  const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: "15m" });
  const refreshToken = jwt.sign({ userId: user.id }, REFRESH_SECRET, { expiresIn: "7d" });
  
  // Store tokens in HTTP-only cookies (secure against XSS)
  res.cookie("accessToken", token, { httpOnly: true, secure: true });
  res.cookie("refreshToken", refreshToken, { httpOnly: true, secure: true });
  
  // Also store session in Redis for revocation ability
  await redis.set(`session:${user.id}`, token, "EX", 900);
});
</code></pre>
<hr />
<h2><strong>Security Considerations</strong></h2>
<h3><strong>Common Attacks &amp; Mitigations</strong></h3>
<table>
<thead>
<tr>
<th><strong>Attack</strong></th>
<th><strong>Sessions</strong></th>
<th><strong>JWT</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>XSS</strong></td>
<td>HttpOnly cookie protects</td>
<td>localStorage vulnerable; use HttpOnly cookie</td>
</tr>
<tr>
<td><strong>CSRF</strong></td>
<td>SameSite cookie + CSRF tokens</td>
<td>SameSite cookie + CSRF tokens</td>
</tr>
<tr>
<td><strong>Replay</strong></td>
<td>Session ID changes on login</td>
<td>Short expiration + refresh tokens</td>
</tr>
<tr>
<td><strong>Theft</strong></td>
<td>Can revoke session</td>
<td>Can't revoke until expiry (use refresh token rotation)</td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/b90bf8c0-4995-4dc6-9e7d-941658aa9363.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>Quick Reference Card</strong></h2>
<p>javascript</p>
<pre><code class="language-javascript">// SESSIONS - Server-side storage
// Pros: Easy logout, small cookie, CSRF protection
// Cons: Needs database, harder to scale
app.use(session({ secret: "key", store: new RedisStore() }));
req.session.userId = userId;

// JWT - Client-side token
// Pros: Stateless, scales well, works across domains
// Cons: Can't revoke easily, larger payload
const token = jwt.sign({ userId }, SECRET, { expiresIn: "1h" });
jwt.verify(token, SECRET);

// COOKIES - Storage mechanism (used with both)
res.cookie("name", "value", { httpOnly: true, secure: true });
req.cookies.name
</code></pre>
<hr />
<h2><strong>Final Summary</strong></h2>
<table>
<thead>
<tr>
<th><strong>Use Case</strong></th>
<th><strong>Recommendation</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Traditional web app (Rails/Django/Express with views)</td>
<td><strong>Sessions</strong> in HTTP-only cookies</td>
</tr>
<tr>
<td>Modern SPA (React/Vue/Angular) on same domain</td>
<td><strong>JWT</strong> in HTTP-only cookie</td>
</tr>
<tr>
<td>REST API for multiple clients</td>
<td><strong>JWT</strong> in Authorization header</td>
</tr>
<tr>
<td>Microservices architecture</td>
<td><strong>JWT</strong> for internal communication</td>
</tr>
<tr>
<td>Mobile app backend</td>
<td><strong>JWT</strong> with refresh tokens</td>
</tr>
<tr>
<td>Banking/financial app</td>
<td><strong>Sessions</strong> with strict security</td>
</tr>
<tr>
<td>Simple personal project</td>
<td>Either works; choose simpler option</td>
</tr>
</tbody></table>
<p><strong>The golden rule:</strong> Use HTTP-only, Secure, SameSite cookies regardless of whether you store a session ID or JWT. Store as little sensitive data as possible. Always use HTTPS in production.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Map and Set]]></title><description><![CDATA[Better Ways to Store Data
For years, JavaScript developers relied on plain objects {} for key-value storage and arrays [] for lists. But objects and arrays have limitations.
Enter Map and Set – two po]]></description><link>https://blog.portfoliohub.in/javascript-map-and-set</link><guid isPermaLink="true">https://blog.portfoliohub.in/javascript-map-and-set</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Thu, 16 Apr 2026 19:27:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/7d8e5bdd-1e34-40a5-af56-49925335235d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3><strong>Better Ways to Store Data</strong></h3>
<p>For years, JavaScript developers relied on plain objects <code>{}</code> for key-value storage and arrays <code>[]</code> for lists. But objects and arrays have limitations.</p>
<p>Enter <strong>Map</strong> and <strong>Set</strong> – two powerful data structures introduced in ES6 that solve real problems.</p>
<p>Let’s explore what they are, how they differ from traditional structures, and when you should use them.</p>
<h3>What is a Map?</h3>
<p>A Map is a collection of key-value pairs where keys can be any data type (objects, functions, numbers, strings, etc.)</p>
<p>No guartee order of key, key can be any orders, may be sorted or not sorted</p>
<p>they remember the original insertion order.</p>
<h3>The Problem with Plain Objects</h3>
<p>Traditional objects have two major flaws:</p>
<ol>
<li><p><strong>Keys are always strings</strong> (or symbols). If you use a number or object as a key, it gets converted to a string.</p>
</li>
<li><p><strong>Prototype chain pollution</strong> – properties like <code>toString</code> can accidentally interfere with your data.</p>
</li>
</ol>
<pre><code class="language-javascript">// The problem with objects
const obj = {};
obj[1] = "number one";
obj["1"] = "string one"; // Overwrites the previous!

console.log(obj[1]); // "string one" - lost the number key

// Object keys cause issues
const user = { name: "Alice" };
obj[user] = "user data";
console.log(obj["[object Object]"]); // "user data" - key got stringified!
</code></pre>
<h3><strong>How Map Solves This</strong></h3>
<pre><code class="language-javascript">const map = new Map();

// Keys keep their original type
map.set(1, "number one");
map.set("1", "string one");
map.set({ name: "Alice" }, "user data");

console.log(map.get(1));  // "number one" - separate entry
console.log(map.get("1")); // "string one" - separate entry

// Object key works as expected
const alice = { name: "Alice" };
map.set(alice, { email: "alice@example.com" });
console.log(map.get(alice)); // { email: "alice@example.com" }
</code></pre>
<h3><strong>Map Methods at a Glance</strong></h3>
<table>
<thead>
<tr>
<th><strong>Method</strong></th>
<th><strong>Description</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>set(key, value)</code></td>
<td>Adds or updates an entry</td>
</tr>
<tr>
<td><code>get(key)</code></td>
<td>Retrieves a value</td>
</tr>
<tr>
<td><code>has(key)</code></td>
<td>Checks if key exists</td>
</tr>
<tr>
<td><code>delete(key)</code></td>
<td>Removes an entry</td>
</tr>
<tr>
<td><code>clear()</code></td>
<td>Removes all entries</td>
</tr>
<tr>
<td><code>size</code></td>
<td>Returns number of entries</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">const scores = new Map();
scores.set("Alice", 95);
scores.set("Bob", 87);

console.log(scores.has("Alice")); // true
console.log(scores.size);         // 2
scores.delete("Bob");
console.log(scores.size);         // 1
</code></pre>
<h2><strong>What is a Set?</strong></h2>
<p>A <strong>Set</strong> is a collection of <strong>unique values</strong> – no duplicates allowed. Values can be of any type, and insertion order is preserved.</p>
<h3><strong>The Problem with Arrays</strong></h3>
<p>Arrays allow duplicates, which often requires extra code to handle:</p>
<pre><code class="language-javascript">// Array with duplicates
const tags = ["js", "react", "js", "node", "react", "css"];

// Removing duplicates manually
const uniqueTags = [];
for (const tag of tags) {
  if (!uniqueTags.includes(tag)) {
    uniqueTags.push(tag);
  }
}
console.log(uniqueTags); // ["js", "react", "node", "css"] - 4 lines of code
</code></pre>
<h3><strong>How Set Solves This</strong></h3>
<pre><code class="language-plaintext">const tags = ["js", "react", "js", "node", "react", "css"];
const uniqueTags = new Set(tags);

console.log(uniqueTags); // Set(4) { "js", "react", "node", "css" }

// Convert back to array if needed
console.log([...uniqueTags]); // ["js", "react", "node", "css"]
</code></pre>
<p><strong>One line. No duplicates. Perfect.</strong>  </p>
<p><strong>Set Methods at a Glance</strong></p>
<table>
<thead>
<tr>
<th><strong>Method</strong></th>
<th><strong>Description</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>add(value)</code></td>
<td>Adds a value (ignores duplicates)</td>
</tr>
<tr>
<td><code>has(value)</code></td>
<td>Checks if value exists</td>
</tr>
<tr>
<td><code>delete(value)</code></td>
<td>Removes a value</td>
</tr>
<tr>
<td><code>clear()</code></td>
<td>Removes all values</td>
</tr>
<tr>
<td><code>size</code></td>
<td>Returns number of values</td>
</tr>
</tbody></table>
<pre><code class="language-javascript">const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // ignored - already exists

console.log(fruits.size); // 2
console.log(fruits.has("banana")); // true

fruits.delete("banana");
console.log(fruits.size); // 1
</code></pre>
<h3><strong>Map vs Object</strong></h3>
<table>
<thead>
<tr>
<th><strong>Feature</strong></th>
<th><strong>Map</strong></th>
<th><strong>Object</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Key types</td>
<td>Any (objects, functions, primitives)</td>
<td>Strings &amp; Symbols only</td>
</tr>
<tr>
<td>Key order</td>
<td>Preserves insertion order</td>
<td>No guaranteed order (for non-integer keys)</td>
</tr>
<tr>
<td>Size property</td>
<td><code>map.size</code></td>
<td><code>Object.keys(obj).length</code></td>
</tr>
<tr>
<td>Performance</td>
<td>Better for frequent additions/removals</td>
<td>Slower for large dynamic operations</td>
</tr>
<tr>
<td>Prototype</td>
<td>No prototype pollution</td>
<td>Has prototype chain</td>
</tr>
<tr>
<td>Iteration</td>
<td>Directly iterable (<code>for...of</code>)</td>
<td>Needs <code>Object.entries()</code></td>
</tr>
</tbody></table>
<h3><strong>Set vs Array</strong></h3>
<table>
<thead>
<tr>
<th><strong>Feature</strong></th>
<th><strong>Set</strong></th>
<th><strong>Array</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Duplicates</td>
<td>Not allowed</td>
<td>Allowed</td>
</tr>
<tr>
<td>Order</td>
<td>Preserves insertion order</td>
<td>Preserves order</td>
</tr>
<tr>
<td>Access by index</td>
<td>No (use <code>has()</code> or iteration)</td>
<td>Yes (<code>arr[0]</code>)</td>
</tr>
<tr>
<td>Performance</td>
<td>Faster for existence checks (<code>has()</code>)</td>
<td>Slower (<code>includes()</code> or <code>indexOf()</code>)</td>
</tr>
<tr>
<td>Use case</td>
<td>Uniqueness &amp; membership</td>
<td>Ordered lists with possible duplicates</td>
</tr>
</tbody></table>
<h3><strong>Use Map when:</strong></h3>
<ul>
<li><p>Keys are unknown until runtime (dynamic)</p>
</li>
<li><p>Keys need to be objects, numbers, or functions</p>
</li>
<li><p>You need frequent addition and removal of key-value pairs</p>
</li>
<li><p>Order of insertion matters</p>
</li>
<li><p>You want to avoid prototype chain issues</p>
</li>
<li><p>frequency / count / number of times</p>
</li>
<li><p>occurrence(s)</p>
</li>
<li><p>mapping / associate / pairing</p>
</li>
<li><p>store extra info for each element</p>
</li>
<li><p>group by something (e.g., anagrams grouping)</p>
</li>
<li><p>find most / least frequent element</p>
</li>
<li><p>accumulate sums per category (e.g., total score per player)</p>
</li>
<li><p>store index/position of elements</p>
</li>
</ul>
<h3><strong>Use Set when:</strong></h3>
<ul>
<li><p>You need a collection of unique values</p>
</li>
<li><p>You frequently check if a value exists</p>
</li>
<li><p>You want to remove duplicates from an array</p>
</li>
<li><p>Order of insertion matters</p>
</li>
<li><p>unique / distinct</p>
</li>
<li><p>duplicate / remove duplicates</p>
</li>
<li><p>exists / contains / present</p>
</li>
<li><p>intersection / union / difference of elements</p>
</li>
<li><p>first repeating / first non-repeating</p>
</li>
<li><p>already seen before?</p>
</li>
<li><p>check membership in O(1)</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Join SQL]]></title><description><![CDATA[Inner Join

Will merge those rows and column are referece to each OtherThis will only return students who got the internship, and It will return the internship which are gotten by students  
Students ]]></description><link>https://blog.portfoliohub.in/join-sql</link><guid isPermaLink="true">https://blog.portfoliohub.in/join-sql</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Thu, 16 Apr 2026 11:57:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/0880fea7-e31c-48f3-96ed-4c24f56bcfae.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ol>
<li>Inner Join</li>
</ol>
<p>Will merge those rows and column are referece to each Other<br />This will only return students who got the internship, and It will return the internship which are gotten by students  </p>
<p>Students ID mentioned in Internship table and students table</p>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[JavaScript Destructuring: Stop Writing Repetitive Code**
If you’ve ever found yourself writing const name = user.name or const first = arr[0] over and over again, you’re doing extra work.
JavaScript h]]></description><link>https://blog.portfoliohub.in/destructuring-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/destructuring-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 15 Apr 2026 18:14:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/06159989-9e89-43c3-9b38-59985a4b83ba.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>JavaScript Destructuring: Stop Writing Repetitive Code**</h2>
<p>If you’ve ever found yourself writing <code>const name =</code> <a href="http://user.name"><code>user.name</code></a> or <code>const first = arr[0]</code> over and over again, you’re doing extra work.</p>
<p>JavaScript has a beautiful feature called <strong>destructuring</strong> that lets you unpack values from arrays and properties from objects into distinct variables—in one clean line.</p>
<p>Let’s dive into what destructuring means, how it works with arrays and objects, setting default values, and why you should start using it today.</p>
<h2><strong>What Destructuring Means</strong></h2>
<p><strong>Destructuring</strong> is a syntax that allows you to extract data from arrays or objects and assign them to variables using a pattern that mirrors the original structure.</p>
<p>Think of it as "unpacking" your data.  </p>
<p><strong>Destructuring Arrays</strong></p>
<p>With arrays, destructuring pulls values by their <strong>position</strong>.</p>
<h3><strong>Without Destructuring (The Old Way)</strong></h3>
<pre><code class="language-plaintext">const colors = ["red", "green", "blue"];

const first = colors[0];
const second = colors[1];
const third = colors[2];

console.log(first, second, third); // red green blue
</code></pre>
<h3><strong>With Destructuring</strong></h3>
<pre><code class="language-plaintext">const colors = ["red", "green", "blue"];
const [first, second, third] = colors;

console.log(first, second, third); // red green blue
</code></pre>
<p>You can also skip items using empty commas:  </p>
<pre><code class="language-plaintext">const [, , third] = ["red", "green", "blue"];
console.log(third); // blue
</code></pre>
<h2><strong>Destructuring Objects</strong></h2>
<p>Object destructuring uses the <strong>property names</strong>—not order.</p>
<h3><strong>Before Destructuring</strong></h3>
<pre><code class="language-plaintext">const user = {
  name: "Alice",
  age: 28,
  city: "Paris"
};

const name = user.name;
const age = user.age;
const city = user.city;

console.log(name, age, city); // Alice 28 Paris
</code></pre>
<h3><strong>After Destructuring</strong></h3>
<pre><code class="language-plaintext">const user = {
  name: "Alice",
  age: 28,
  city: "Paris"
};

const { name, age, city } = user;

console.log(name, age, city); // Alice 28 Paris
</code></pre>
<p>You can also assign to different variable names:</p>
<pre><code class="language-plaintext">const { name: userName, age: userAge } = user;
console.log(userName, userAge); // Alice 28
</code></pre>
<h2><strong>Default Values</strong></h2>
<p>What if a property or array element is missing? Destructuring lets you set <strong>default values</strong> to avoid <code>undefined</code>.</p>
<h3><strong>Arrays with defaults</strong></h3>
<pre><code class="language-plaintext">const [a = 1, b = 2] = [10];
console.log(a, b); // 10 2 (only a gets 10, b uses default)
</code></pre>
<h3><strong>Objects with defaults</strong></h3>
<pre><code class="language-plaintext">const { name, role = "guest" } = { name: "Bob" };
console.log(name, role); // Bob guest
</code></pre>
<h2><strong>Suggestions for Using Destructuring</strong></h2>
<ul>
<li><p><strong>Use object destructuring</strong> when you need multiple properties from the same object.</p>
</li>
<li><p><strong>Use array destructuring</strong> for swapping variables or getting first/second items.</p>
</li>
<li><p><strong>Always provide defaults</strong> when data might be missing.</p>
</li>
<li><p><strong>Destructure function parameters</strong> to make functions self-documenting.</p>
</li>
<li><p><strong>Avoid over-destructuring</strong> – don’t go more than 2 levels deep without a good reason.</p>
</li>
</ul>
<h2><strong>Final Thought</strong></h2>
<p>Destructuring isn’t just a "cool trick." It’s a fundamental tool that makes your JavaScript cleaner, safer, and more expressive.</p>
]]></content:encoded></item><item><title><![CDATA[Synchronous vs Asynchronous JavaScript]]></title><description><![CDATA[The Pulse of the Web: Understanding Synchronous vs. Asynchronous JavaScript
In the world of programming, timing is everything. If you've ever used an app that froze while loading a photo, or a website]]></description><link>https://blog.portfoliohub.in/synchronous-vs-asynchronous-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/synchronous-vs-asynchronous-javascript</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Fri, 03 Apr 2026 19:29:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/0c9d2941-6ad4-4578-b979-2ac2ea22aa9c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>The Pulse of the Web: Understanding Synchronous vs. Asynchronous JavaScript</h2>
<p>In the world of programming, timing is everything. If you've ever used an app that froze while loading a photo, or a website that felt "snappy" even while fetching data, you’ve experienced the difference between <strong>synchronous</strong> and <strong>asynchronous</strong> code.</p>
<p>For a language like JavaScript, which powers almost everything we do online, understanding these concepts is the key to building smooth, professional applications.</p>
<h3>1. What is Synchronous Code? (The Waiting Game)</h3>
<p>By default, JavaScript is <strong>synchronous</strong> and <strong>single-threaded</strong>. This means it executes code line-by-line, in order. It completes one task before moving on to the next.</p>
<p><strong>The Step-by-Step Execution:</strong></p>
<ol>
<li><p>Execute Line 1.</p>
</li>
<li><p>Wait for Line 1 to finish.</p>
</li>
<li><p>Execute Line 2.</p>
</li>
</ol>
<p><strong>Everyday Example:</strong> Think of a single-file line at a coffee shop. The barista takes one order, makes that coffee, and hands it over <em>before</em> talking to the next person in line. If one customer orders ten complex drinks, everyone else stands still and waits.</p>
<p><strong>Code example:</strong></p>
<pre><code class="language-plaintext">console.log("Order coffee");
console.log("Pay");
console.log("Wait for coffee");
console.log("Leave");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Order coffee
Pay
Wait for coffee
Leave
</code></pre>
<p><strong>Key point:</strong><br />If one step takes 5 seconds (e.g., making coffee), <strong>nothing else happens</strong> during those 5 seconds.</p>
<h3>2. The Problem: Blocking Code</h3>
<p>When a task takes a long time to finish (like a heavy calculation or a massive file download) in a synchronous environment, it creates <strong>blocking code</strong>.</p>
<p>Because JavaScript is "single-threaded," the entire browser tab "freezes" while it waits for that one line to finish. You can’t click buttons, scroll, or interact with the page. This leads to a poor user experience.</p>
<p><strong>Everyday example:</strong><br />At a busy coffee shop with a buzzer.</p>
<ul>
<li><p>You order → pay → get buzzer → sit down and check your phone.</p>
</li>
<li><p>Buzzer rings → you pick up coffee → leave.</p>
</li>
<li><p>Other customers can order while you wait.</p>
</li>
</ul>
<p><strong>Code example:</strong></p>
<p>javascript</p>
<pre><code class="language-plaintext">console.log("Order coffee");
console.log("Pay");

setTimeout(() =&gt; {
  console.log("Coffee ready — pick up");
}, 3000);

console.log("Sit down and check phone");

// Output:
// Order coffee
// Pay
// Sit down and check phone
// (3 seconds later) Coffee ready — pick up
</code></pre>
<p><strong>Key point:</strong><br />The program doesn’t freeze while waiting.</p>
<p>Everyday example: At a busy coffee shop with a buzzer.</p>
<p>You order → pay → get buzzer → sit down and check your phone.</p>
<p>Buzzer rings → you pick up coffee → leave.</p>
<p>Other customers can order while you wait.</p>
<p>Code example:</p>
<p>javascript console.log("Order coffee"); console.log("Pay");</p>
<p>setTimeout(() =&gt; { console.log("Coffee ready — pick up"); }, 3000);</p>
<p>console.log("Sit down and check phone");</p>
<p>// Output: // Order coffee // Pay // Sit down and check phone // (3 seconds later) Coffee ready — pick up Key point: The program doesn’t freeze while waiting.</p>
<ol>
<li>Why JavaScript Needs Asynchronous Behavior JavaScript is single-threaded (one thing at a time by default). If it waited for every slow task, the whole page would freeze.</li>
</ol>
<p>Real-world scenarios requiring async:</p>
<p>Scenario If synchronous (bad) If asynchronous (good) Fetching user data from a server Page freezes until data arrives Page stays responsive, shows spinner Reading a large file App unresponsive for seconds App continues, file loads in background Setting a reminder for 10 seconds later Blocks everything for 10 seconds Timer runs quietly, other code runs 4. Examples Like API Calls or Timers Timer (already shown) setTimeout / setInterval</p>
<p>API call (using fetch)</p>
<p>javascript console.log("Requesting user data...");</p>
<p>fetch("<a href="https://jsonplaceholder.typicode.com/users/1">https://jsonplaceholder.typicode.com/users/1</a>") .then(response =&gt; response.json()) .then(user =&gt; console.log("User received:", user.name));</p>
<p>console.log("This runs while waiting for the network."); Output order:</p>
<p>text Requesting user data... This runs while waiting for the network. User received: Leanne Graham Event listener (another async pattern)</p>
<p>javascript button.addEventListener("click", () =&gt; { console.log("Button clicked — but only when user acts"); }); 5. Problems That Occur with Blocking Code Blocking code = synchronous code that takes a long time.</p>
<p>Example of bad blocking code:</p>
<p>javascript console.log("Start");</p>
<p>// Block for 3 seconds let end = Date.now() + 3000; while (Date.now() &lt; end) { // do nothing — just wait }</p>
<p>console.log("End"); While this runs:</p>
<p>No buttons respond</p>
<p>No animations update</p>
<p>Browser might show "page unresponsive"</p>
<p>User impact:</p>
<p>Form can’t be submitted</p>
<p>Spinners don’t animate</p>
<p>User thinks the app crashed</p>
<p>Real danger: A slow database query or large loop can freeze the entire UI for seconds or minutes.</p>
<p>Visual Summary (Mental Model) Synchronous (blocking): Task A [====] → Task B [====] → Task C [====] Time moves →</p>
<p>Asynchronous (non-blocking): Task A [start] → (waits) Task B [========] (finishes early) Task C [start] → finishes Task A [resumes] → finishes</p>
<p>Time moves → with gaps filled by other work.</p>
<p>Suggested Teaching Flow Start with step-by-step synchronous – simple console logs.</p>
<p>Introduce a delay – use setTimeout to show waiting.</p>
<p>Show the freeze – bad blocking loop (mention never use this in real code).</p>
<p>Explain the need – fetch API example (even fake fetch).</p>
<p>Introduce event loop intuitively – “JavaScript hands slow tasks to the browser, then comes back later.”</p>
<p>End with real-world UI – loading spinners, responsive buttons.  </p>
<p>Summary :<br />Synchronus task run on maint thred if we align heavy task with sync it will block the next pipeline task.<br />Async aprroach - Will assure that given task will be done in after some period and will notify usiing call back</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Async/Await in JavaScript]]></title><description><![CDATA[Why async/await was introduced
JavaScript originally relied on callbacks and then Promises to handle asynchronous operations. While Promises improved readability compared to nested callbacks, complex ]]></description><link>https://blog.portfoliohub.in/understanding-async-await-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/understanding-async-await-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Sat, 28 Mar 2026 03:17:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/09570072-8475-4026-8d64-98b7409af62a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Why async/await was introduced</h2>
<p>JavaScript originally relied on callbacks and then Promises to handle asynchronous operations. While Promises improved readability compared to nested callbacks, complex chains could still become hard to follow. Async/await was introduced as syntactic sugar over Promises to make asynchronous code look and behave more like synchronous code.</p>
<h2>How async functions work</h2>
<p>An <code>async</code> function always returns a <strong>Promise</strong>. When you mark a function with <code>async</code>, it automatically wraps any returned value in a resolved promise, and any thrown error in a rejected promise.</p>
<p>You can use the <code>await</code> keyword to pause execution until the awaited Promise resolves. This makes asynchronous code easier to reason about.</p>
<pre><code class="language-plaintext">// Regular function
function getData() {
  return "Hello";
}

// Async function (returns a promise)
async function getDataAsync() {
  return "Hello";
}

console.log(getData()); // "Hello"
console.log(getDataAsync()); // Promise {&lt;fulfilled&gt;: "Hello"}


async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}
</code></pre>
<h3><strong>Await keyword concept</strong></h3>
<p>The <code>await</code> keyword can only be used inside <code>async</code> functions. It <strong>pauses</strong> the execution of the async function until the promise resolves or rejects, then returns the resolved value or throws an error.</p>
<pre><code class="language-plaintext">async function getUserData() {
  // Pauses here until fetch completes
  const response = await fetch('https://api.example.com/user');
  // Then continues here
  const data = await response.json();
  return data;
}
</code></pre>
<h3><strong>Error handling with async code</strong></h3>
<p>Error handling in async/await uses traditional <code>try/catch</code> blocks, making it more intuitive than <code>.catch()</code> with promises.</p>
<pre><code class="language-plaintext">async function fetchUserData() {
  try {
    const response = await fetch('https://api.example.com/user');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch user data:', error.message);
    throw error; // Re-throw if needed
  }
}
</code></pre>
<h3><strong>Comparison with promises</strong></h3>
<ul>
<li><p><strong>Promises</strong>: Require <code>.then()</code> and <code>.catch()</code> chaining.</p>
</li>
<li><p><strong>Async/await</strong>: Allows linear, synchronous-looking code.</p>
</li>
</ul>
<p>Example with Promises:</p>
<pre><code class="language-plaintext">fetch('https://api.example.com/data')
  .then(response =&gt; response.json())
  .then(data =&gt; console.log(data))
  .catch(error =&gt; console.error(error));
</code></pre>
<p>Example with async/await:</p>
<pre><code class="language-plaintext">async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
</code></pre>
<h2><strong>Key Takeaways</strong></h2>
<ol>
<li><p><strong>Always use try/catch</strong> for error handling in async functions</p>
</li>
<li><p><strong>Remember that async functions always return promises</strong> - you can't get the raw value directly</p>
</li>
<li><p><strong>Use Promise.all for parallel operations</strong> to avoid unnecessary waiting</p>
</li>
<li><p><strong>Don't forget that await only works inside async functions</strong> (unless using top-level await in modules)</p>
</li>
<li><p><strong>Async/await doesn't make code faster</strong> - it just makes it easier to reason about</p>
</li>
</ol>
<p>Async/await transforms asynchronous JavaScript from a callback maze into code that reads like synchronous logic while maintaining all the non-blocking benefits of promises.</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[What Spread Operator Does ?
The spread operator (...) expands an iterable (like an array or object) into individual elements.Think of it as taking items out of a box and laying them out individually.
]]></description><link>https://blog.portfoliohub.in/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/spread-vs-rest-operators-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Thu, 26 Mar 2026 19:44:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/5e7955c3-b805-45af-ae8f-420808f9df66.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>What Spread Operator Does ?</strong></h2>
<p>The <strong>spread operator</strong> (<code>...</code>) <strong>expands</strong> an iterable (like an array or object) into individual elements.<br />Think of it as taking items out of a box and laying them out individually.</p>
<h3>1. Using Spread with Arrays**</h3>
<p>It is commonly used to combine arrays or create shallow copies.</p>
<h3><strong>Copying Arrays</strong></h3>
<pre><code class="language-plaintext">const original = [1, 2, 3];
const copy = [...original]; // Creates a shallow copy

console.log(copy); // [1, 2, 3]
console.log(original === copy); // false (different references)
</code></pre>
<h3><strong>Combining Arrays</strong></h3>
<pre><code class="language-plaintext">const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

console.log(combined); // [1, 2, 3, 4, 5, 6]
</code></pre>
<h3><strong>Adding Elements</strong></h3>
<pre><code class="language-plaintext">const fruits = ['apple', 'banana'];
const moreFruits = ['orange', ...fruits, 'grape'];

console.log(moreFruits); // ['orange', 'apple', 'banana', 'grape']
</code></pre>
<h2><strong>Using Spread with Objects</strong></h2>
<h3><strong>Copying Objects</strong></h3>
<pre><code class="language-plaintext">const user = { name: 'John', age: 30 };
const userCopy = { ...user };

console.log(userCopy); // { name: 'John', age: 30 }
</code></pre>
<h3><strong>Merging Objects</strong></h3>
<pre><code class="language-plaintext">const user = { name: 'John', age: 30 };
const address = { city: 'New York', country: 'USA' };
const profile = { ...user, ...address };

console.log(profile);
// { name: 'John', age: 30, city: 'New York', country: 'USA' }
</code></pre>
<h3><strong>Overriding Properties</strong></h3>
<pre><code class="language-plaintext">const defaultSettings = { theme: 'light', fontSize: 14, notifications: true };
const userSettings = { theme: 'dark', fontSize: 16 };

const finalSettings = { ...defaultSettings, ...userSettings };
console.log(finalSettings);
// { theme: 'dark', fontSize: 16, notifications: true }
</code></pre>
<h2><strong>What Rest Operator Does</strong></h2>
<p>The <strong>Rest</strong> operator does the exact opposite: it "collects" multiple individual elements and bunches them into a single array. It is primarily used in function parameters or destructuring.</p>
<h2><strong>Using Rest with Function Parameters</strong></h2>
<pre><code class="language-plaintext">function logItems(category, ...items) { 
console.log(Category: ${category}); 
console.log(Items: ${items.join(', ')}); 
}

logItems('Fruits', 'apple', 'banana', 'orange');

// Category: Fruits
// Items: apple, banana, orange
</code></pre>
<h3><strong>Destructuring Arrays</strong></h3>
<pre><code class="language-plaintext">const scores = [98, 87, 92, 85, 88];
const [first, second, ...rest] = scores;

console.log(first);  // 98
console.log(second); // 87
console.log(rest);   // [92, 85, 88]
</code></pre>
<h3><strong>Destructuring Objects</strong></h3>
<pre><code class="language-plaintext">const person = {
    name: 'Alice',
    age: 28,
    city: 'Boston',
    country: 'USA'
};

const { name, age, ...location } = person;
console.log(name);     // 'Alice'
console.log(age);      // 28
console.log(location); // { city: 'Boston', country: 'USA' }
</code></pre>
<h2>⚖️ Key Differences: Spread vs. Rest</h2>
<table style="min-width:75px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p><strong>Feature</strong></p></td><td><p><strong>Spread Operator</strong></p></td><td><p><strong>Rest Operator</strong></p></td></tr><tr><td><p><strong>Action</strong></p></td><td><p><strong>Expands</strong> (Unpacks)</p></td><td><p><strong>Collects</strong> (Packs)</p></td></tr><tr><td><p><strong>Placement</strong></p></td><td><p>Usually in an array/object literal or function call</p></td><td><p>Usually in function parameters or destructuring</p></td></tr><tr><td><p><strong>End Result</strong></p></td><td><p>Individual values</p></td><td><p>A single Array</p></td></tr></tbody></table>

<h2><strong>Practical Real-World Use Cases</strong></h2>
<h3><strong>1. Immutable State Updates (React)</strong></h3>
<pre><code class="language-plaintext">// Adding an item to an array immutably
const [todos, setTodos] = useState(['Learn React']);
const addTodo = (newTodo) =&gt; {
    setTodos([...todos, newTodo]);
};

// Updating an object immutably
const [user, setUser] = useState({ name: 'John', age: 30 });
const updateAge = () =&gt; {
    setUser({ ...user, age: user.age + 1 });
};
</code></pre>
<h3><strong>2. Function Argument Handling</strong></h3>
<pre><code class="language-plaintext">// Creating flexible functions
function createUser(name, email, ...additionalInfo) {
    const user = { name, email };
    
    if (additionalInfo.length &gt; 0) {
        user.metadata = additionalInfo;
    }
    
    return user;
}

const user = createUser('Bob', 'bob@email.com', 'premium', 'joined-2023');
console.log(user);
// { name: 'Bob', email: 'bob@email.com', metadata: ['premium', 'joined-2023'] }
</code></pre>
<h3><strong>3. Math Operations</strong></h3>
<pre><code class="language-plaintext">const numbers = [5, 12, 8, 130, 44];

// Using spread with Math functions
const max = Math.max(...numbers);  // 130
const min = Math.min(...numbers);  // 5

console.log(max, min);
</code></pre>
<h3><strong>4. Converting NodeList to Array</strong></h3>
<pre><code class="language-plaintext">// Convert DOM elements collection to real array
const divs = document.querySelectorAll('div');
const divArray = [...divs];

// Now you can use array methods
divArray.map(div =&gt; div.classList.add('highlight'));
</code></pre>
<h3><strong>5. Creating Shallow Clones with Modifications</strong></h3>
<pre><code class="language-plaintext">const originalTodo = {
    id: 1,
    text: 'Buy groceries',
    completed: false
};

const updatedTodo = {
    ...originalTodo,
    completed: true,
    completedAt: new Date().toISOString()
};

console.log(updatedTodo);
// { id: 1, text: 'Buy groceries', completed: true, completedAt: '2024-01-15T10:30:00.000Z' }
</code></pre>
<h3><strong>6. Dynamic Function Calls</strong></h3>
<pre><code class="language-plaintext">function calculate(operation, ...numbers) {
    switch(operation) {
        case 'sum':
            return numbers.reduce((a, b) =&gt; a + b, 0);
        case 'multiply':
            return numbers.reduce((a, b) =&gt; a * b, 1);
        default:
            return null;
    }
}

console.log(calculate('sum', 1, 2, 3, 4));        // 10
console.log(calculate('multiply', 2, 3, 4));      // 24

// Using with spread to pass array
const values = [5, 10, 15];
console.log(calculate('sum', ...values));          // 30
</code></pre>
<h2><strong>Key Takeaways</strong></h2>
<ol>
<li><p><strong>Spread expands</strong> - takes an array/object and spreads it into individual elements</p>
</li>
<li><p><strong>Rest collects</strong> - takes individual elements and collects them into an array/object</p>
</li>
<li><p><strong>Both use</strong> <code>...</code> <strong>syntax</strong> but serve opposite purposes</p>
</li>
<li><p><strong>Use spread for</strong>: copying, merging, passing array elements as arguments</p>
</li>
<li><p><strong>Use rest for</strong>: collecting function arguments, destructuring remaining items</p>
</li>
</ol>
<p>The spread and rest operators are powerful tools that enable more readable and maintainable code when working with arrays, objects, and function parameters in modern JavaScript.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Error Handling - Complete Guide]]></title><description><![CDATA[1. What Errors Are in JavaScript
Errors in JavaScript are objects that indicate something went wrong during execution. They interrupt the normal flow of your program.
Types of Errors:

Syntax Error - ]]></description><link>https://blog.portfoliohub.in/javascript-error-handling-complete-guide</link><guid isPermaLink="true">https://blog.portfoliohub.in/javascript-error-handling-complete-guide</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 25 Mar 2026 07:08:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/4d1a4fa6-8b1e-4220-b985-d4a06f97d649.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>1. What Errors Are in JavaScript</strong></h2>
<p>Errors in JavaScript are objects that indicate something went wrong during execution. They interrupt the normal flow of your program.</p>
<h3><strong>Types of Errors:</strong></h3>
<ol>
<li><p><strong>Syntax Error</strong> - Code can't be parsed<br />// console.log('Hello' // Missing closing parenthesis</p>
</li>
<li><p><strong>Reference Error</strong> - Variable doesn't exist<br />console.log(undefinedVariable); // ReferenceError: undefinedVariable is not defined</p>
</li>
<li><p><strong>Type Error</strong> - Operation on wrong data type<br />const num = 5;<br />num(); // TypeError: num is not a function</p>
</li>
<li><p><strong>Range Error</strong> - Value out of range<br />const arr = new Array(-1); // RangeError: Invalid array length</p>
</li>
<li><p><strong>Network Error</strong> - Failed network request<br />fetch('<a href="https://invalid-url">https://invalid-url</a>'); // NetworkError</p>
</li>
<li><p><strong>Custom Errors</strong> - Your own defined errors<br />throw new Error('Something went wrong');</p>
</li>
</ol>
<h3>2. <strong>Using Try and Catch Blocks</strong></h3>
<p>Try-catch allows you to handle errors gracefully without crashing your application.</p>
<h3><strong>Basic Structure:</strong></h3>
<pre><code class="language-plaintext">try { 
    let result = JSON.parse("invalid json"); 

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

}
</code></pre>
<h3>Flow:</h3>
<ul>
<li><p><code>try</code> → run code</p>
</li>
<li><p><code>catch</code> → handle error if occurs</p>
</li>
</ul>
<h3><strong>3. The Finally Block</strong></h3>
<p><strong>finally</strong> runs regardless of whether an error occurred or not - perfect for cleanup operations.<br />Use Case:</p>
<pre><code class="language-javascript">try {
    console.log('Opening database connection...');
    const conn = await db.connect();
    
    // Do something with connection
    const data = await conn.query('SELECT * FROM users');
    
    return data;
    
} catch (error) {
    console.error('Query failed:', error);
    throw error;
    
} finally {
    console.log("ALWAYS runs - even if there was an error");
    // 
    console.log('Closing database connection...');
    await conn.close(); // Ensures connection is always closed
}
</code></pre>
<ul>
<li><p>Closing DB connection</p>
</li>
<li><p>Cleaning resources</p>
</li>
</ul>
<h2><strong>4. Throwing Custom Errors</strong></h2>
<p>You can manually create errors using <code>throw</code>. Create meaningful, specific errors for better debugging.</p>
<h3><strong>Creating Custom Error Classes:</strong></h3>
<pre><code class="language-javascript">class ApiError extends Error{
    constructor(statuscode, message){
        super(message),
        this.statuscode = statuscode,
        this.isOperational = true,
        Error.captureStackTrace(this, this.constructor)
    }
    static badRequest(message = "Bad Request"){
        return new ApiError(400, message)

    }
    static unauthorized(message = "Unauthorized"){
        return new ApiError(401, message)
    }
    static conflict(message = "Conflict"){
        return new ApiError(409, message)
    }
}
export default ApiError
</code></pre>
<pre><code class="language-plaintext">// Base custom error
class AppError extends Error {
    constructor(message, statusCode = 500) {
        super(message);
        this.name = this.constructor.name;
        this.statusCode = statusCode;
        Error.captureStackTrace(this, this.constructor);
    }
}

// Specific error types
class ValidationError extends AppError {
    constructor(message, fields = null) {
        super(message, 400);
        this.fields = fields;
    }
}

class DatabaseError extends AppError {
    constructor(message, originalError = null) {
        super(message, 500);
        this.originalError = originalError;
    }
}

class AuthenticationError extends AppError {
    constructor(message) {
        super(message, 401);
    }
}

class NotFoundError extends AppError {
    constructor(resource) {
        super(`${resource} not found`, 404);
        this.resource = resource;
    }
}
</code></pre>
<h3>5. Why Error Handling Matters</h3>
<h3>🚀 Prevents App Crash</h3>
<p>Without handling:</p>
<pre><code class="language-plaintext">JSON.parse("invalid"); // 💥 crashes app
</code></pre>
<p>With handling:</p>
<pre><code class="language-plaintext">try {
  JSON.parse("invalid");
} catch {
  console.log("Handled safely");
}
</code></pre>
<h3>6. <strong>Graceful Failure - Don't Crash Your App</strong></h3>
<pre><code class="language-plaintext">// BAD: App crashes on error
app.get('/user/:id', async (req, res) =&gt; {
    const user = await User.findById(req.params.id);
    res.json(user); // If user not found, app crashes!
});
</code></pre>
<pre><code class="language-plaintext">// GOOD: Handle errors gracefully
app.get('/user/:id', async (req, res) =&gt; {
    try {
        const user = await User.findById(req.params.id);
        
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            data: user
        });
        
    } catch (error) {
        console.error('Error fetching user:', error);
        res.status(500).json({
            success: false,
            message: 'Unable to fetch user'
        });
    }
});
</code></pre>
<h2><strong>Key Takeaways</strong></h2>
<ol>
<li><p><strong>Always use try-catch</strong> for async operations</p>
</li>
<li><p><strong>Create custom error types</strong> for better debugging</p>
</li>
<li><p><strong>Use finally block</strong> for cleanup operations</p>
</li>
<li><p><strong>Never expose internal errors</strong> to users</p>
</li>
<li><p><strong>Log errors with context</strong> for debugging</p>
</li>
<li><p><strong>Handle unhandled rejections</strong> and exceptions at process level</p>
</li>
<li><p><strong>Graceful failure</strong> keeps your app running even when things go wrong</p>
</li>
</ol>
<p>Error handling isn't just about preventing crashes - it's about creating a robust, debuggable, and user-friendly application!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding String Polyfills]]></title><description><![CDATA[This section focuses on how string methods work internally, why polyfills matter, and how this knowledge helps in interviews.

🧠 What are String Methods?
String methods are built-in JavaScript functi]]></description><link>https://blog.portfoliohub.in/understanding-string-polyfills</link><guid isPermaLink="true">https://blog.portfoliohub.in/understanding-string-polyfills</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Sun, 22 Mar 2026 20:01:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/d896e8ba-4a16-4e24-8890-5468e27cf07b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This section focuses on how string methods work internally, why polyfills matter, and how this knowledge helps in interviews.</p>
<hr />
<h3>🧠 What are String Methods?</h3>
<p>String methods are built-in JavaScript functions used to manipulate and process text.</p>
<p>Examples:</p>
<ul>
<li><p><code>toUpperCase()</code></p>
</li>
<li><p><code>split(',')</code> // Split into array</p>
</li>
<li><p><code>slice()</code></p>
</li>
<li><p><code>substring()</code></p>
</li>
<li><p><code>trim()</code></p>
</li>
<li><p><code>str.length</code> // Get string length</p>
</li>
<li><p><code>charAt(0)</code> // Get character at index</p>
</li>
<li><p><code>indexOf('search')</code> // Find position of substring</p>
</li>
<li><p><code>includes('text')</code> // Check if contains substring</p>
</li>
<li><p><code>slice(0, 5)</code> // Extract portion of string</p>
</li>
<li><p><code>replace('old', 'new')</code> // Replace content</p>
</li>
</ul>
<p>👉 These methods operate on string values and return new strings (strings are immutable).</p>
<h3>How Built-in Methods Work (Conceptually)</h3>
<p>Even though JavaScript provides built-in methods, internally they follow simple logic.</p>
<h4>Example: <code>toUpperCase()()</code></h4>
<p>Conceptual Steps</p>
<ol>
<li><p>Take each character</p>
</li>
<li><p>Get its char code</p>
</li>
<li><p>Check if it's lowercase (<code>a-z</code>)</p>
</li>
<li><p>Subtract 32</p>
</li>
<li><p>Convert back to character</p>
</li>
<li><p>Join result</p>
</li>
</ol>
<pre><code class="language-javascript">String.prototype.upperCaseMethod = function(){
  let res = "";

  for(let i =0; i&lt;this.length; i++){
    let ch = this[i];

    if(ch &gt;= "a" &amp;&amp; ch &lt;= "z"){
    res +=  String.fromCharCode(ch.charCodeAt() -32)
    }else{
      res+= ch
    }
  }
  return res
}
console.log("hello".upperCaseMethod()); // HELLO
console.log("hello".toUpperCase()); // HELLO
</code></pre>
<h4>Example: <code>split()</code></h4>
<pre><code class="language-js">"hello world".split(" ")
</code></pre>
<p>Conceptually:</p>
<ol>
<li><p>Traverse string character by character</p>
</li>
<li><p>Detect separator (" ")</p>
</li>
<li><p>Break string into parts</p>
</li>
<li><p>Store parts in array</p>
</li>
</ol>
<pre><code class="language-javascript"> String.prototype.customSplit = function(separator) {
    const result = [];
    let current = '';
    const str = this;

    for (let i = 0; i &lt; str.length; i++) {
      if (str[i] === separator) {
        result.push(current);
        current = '';
      } else {
        current += str[i];
      }
    }

    result.push(current); // push the last chunk
    return result;
  };

console.log("ravi kumar".customSplit(' '));
console.log("ravi kumar".split(' '));
</code></pre>
<h4>Example: <code>reverse()</code></h4>
<pre><code class="language-javascript">function reverse(str) {
  let res = "";
  for (let i = str.length - 1; i &gt;= 0; i--) {
    res += str[i];
  }
  return res;
}
</code></pre>
<h3>Common Interview String Problems</h3>
<ul>
<li><p>Reverse a string</p>
</li>
<li><p>Check palindrome</p>
</li>
<li><p>Find first non-repeating character</p>
</li>
<li><p>Count occurrences of characters</p>
</li>
<li><p>Remove duplicates</p>
</li>
<li><p>Longest substring without repeating characters</p>
</li>
</ul>
<h3>Why Developers Write Polyfills</h3>
<p>A <strong>polyfill</strong> is a custom implementation of a built-in method.</p>
<h4>Reasons:</h4>
<ul>
<li><p>Understand internal working</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>
<h3>Importance of Understanding Built-in Behavior</h3>
<ul>
<li><p>Helps write optimized code</p>
</li>
<li><p>Avoids misuse of methods</p>
</li>
<li><p>Improves debugging skills</p>
</li>
<li><p>Builds strong fundamentals</p>
</li>
<li><p>Makes problem-solving easier</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What Really Happens When You Use new? ]]></title><description><![CDATA[What the new keyword does

When you create a new instance with the new keyword, a brand new empty object {} is created.

In JavaScript, every function has a prototype. Even objects themselves have a p]]></description><link>https://blog.portfoliohub.in/what-really-happens-when-you-use-new</link><guid isPermaLink="true">https://blog.portfoliohub.in/what-really-happens-when-you-use-new</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Fri, 20 Mar 2026 11:18:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/a6792367-c4fe-458a-beac-73e54018b2f1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>What the <code>new</code> keyword does</h3>
<ul>
<li><p>When you create a new instance with the <code>new</code> keyword, a brand new empty object <code>{}</code> is created.</p>
</li>
<li><p>In JavaScript, every function has a prototype. Even objects themselves have a prototype, so the prototype creates a bridge between the empty object and the function and links them together.</p>
</li>
<li><p>Now the <code>this</code> keyword becomes active after the link and binds the value. Whoever calls it will bind with the caller reference — it binds <code>this</code> to the new object.</p>
</li>
<li><p>If you check any class, there is no return statement. So the final work is done by the <code>new</code> keyword, which automatically returns the newly created object (the constructor explicitly returns the object).</p>
</li>
</ul>
<pre><code class="language-javascript">function TataCar(chassisNumber, modelName) {  
  this.chassisNumber = chassisNumber;  
  this.modelName = modelName;
  this.fuelLevel = 100;  
}

// created own method using prototype
TataCar.prototype.status = function () {
  return `Tata \({this.modelName} #\){this.chassisNumber} | Fuel: ${this.fuelLevel}`;
};

const car1 = new TataCar("MH-101", "Nexon");
const car2 = new TataCar("DL-202", "Harrier");

console.log(car1.modelName);
// console.log(car2.modelName);
// console.log(car1.status());
console.log(car2.status());
</code></pre>
<p><strong>const car1 = new TataCar("MH-101", "Nexon");</strong><br /><strong>const car2 = new TataCar("DL-202", "Harrier");</strong></p>
<p>Behind the scene<br />let car1 = {}; // empty object created<br /><strong>Prototype creates a bridge</strong><br />car1.__proto__ = TataCar.prototype;<br /><strong>Now</strong> <code>car1</code> <strong>is linked to:</strong><br />TataCar.prototype.status<br />car1.status();<br />works even though <code>status</code> is not inside <code>car1</code>.<br />prototype creates bridge between empty object and function</p>
<p><code>this</code> <strong>binds to new object</strong></p>
<p>Inside constructor:<br />this.chassisNumber = "MH-101";<br />this.modelName = "Nexon";<br />this.fuelLevel = 100;</p>
<p>Since <code>this === car1</code>:</p>
<p>No return in constructor:</p>
<p>function TataCar(...) {<br />// no return<br />}</p>
<p><code>new</code> automatically returns object</p>
<pre><code class="language-javascript">console.log(typeof car1.status) // function 
</code></pre>
<pre><code class="language-javascript">car1.status === car2.status // true
</code></pre>
<p>Now check the below factory function</p>
<pre><code class="language-javascript">function createAutoRickshaw(id, route) {
  return {
    id,
    route,
    run() {
      return `Auto \({this.id} running on \){this.route}`;
    },
  };
}
</code></pre>
<p><strong>const auto1 = createAutoRickshaw("UP-1", "Lucknow-kanpu");<br />const auto2 = createAutoRickshaw("UP-2", "Agra-Mathura");</strong></p>
<pre><code class="language-javascript">console.log("TypeOf", typeof auto1.run); // function
</code></pre>
<pre><code class="language-javascript">auto1.run === auto2.run // false
</code></pre>
<p>Constructor functions (with <code>new</code>) share methods via prototype (same reference), while factory functions create a new copy of methods for each object.</p>
<p><code>new</code> → <strong>shared methods (memory efficient)</strong></p>
<p><code>factory</code> → <strong>new method copy each time (memory heavy)</strong></p>
<h3>Summary</h3>
<p>Use <strong>constructor +</strong> <code>new</code> when creating many objects with shared behavior</p>
<ul>
<li>Use <strong>factory functions</strong> for simple, small use cases</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Event Listener Basics]]></title><description><![CDATA[When we click on any element, the target check option is true or false.
Every addEventListener provides three parameters:

event

callback

option


By default, the option is false. Hence, the bubblin]]></description><link>https://blog.portfoliohub.in/event-listener-basics</link><guid isPermaLink="true">https://blog.portfoliohub.in/event-listener-basics</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Fri, 20 Mar 2026 06:14:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/39ce2f89-da59-4e63-9829-b980b787fbc2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When we click on any element, the target check option is <strong>true or false</strong>.</p>
<p>Every <code>addEventListener</code> provides three parameters:</p>
<ol>
<li><p><code>event</code></p>
</li>
<li><p><code>callback</code></p>
</li>
<li><p><code>option</code></p>
</li>
</ol>
<p>By default, the option is <strong>false</strong>. Hence, the <strong>bubbling phase</strong> travels from the target element up to the window, through the DOM tree (bottom → top direction).</p>
<h3>Bubbling Phase (Default: false)</h3>
<pre><code class="language-javascript">child.addEventListener('click', (e)=&gt;{
  console.log(`I am from child || option false =&gt; bubbling phase`);  
})

parent.addEventListener('click', ()=&gt;{
  console.log(`I am from Parent || option false =&gt; bubbling phase`);  
})

body.addEventListener('click', ()=&gt;{
  console.log(`I am from Body || option false =&gt; bubbling phase `);  
})
</code></pre>
<p>Every <code>addEventListener</code> provides three parameters:</p>
<ol>
<li><p>event</p>
</li>
<li><p>callback</p>
</li>
<li><p>option</p>
</li>
</ol>
<p>By default, the option is <strong>false</strong>. Hence, the <strong>bubbling phase</strong> travels from the target element up to the window, through the DOM tree (bottom → top direction).</p>
<h3>Bubbling Phase (Default: false)</h3>
<h3></h3>
<p>Output:</p>
<pre><code class="language-plaintext">I am from child || option false =&gt; bubbling phase
I am from Parent || option false =&gt; bubbling phase
I am from Body || option false =&gt; bubbling phase
</code></pre>
<h2>Stop Bubbling</h2>
<p>To prevent bubbling upward, add <code>e.stopPropagation()</code> to the child.<br />The event will not be delegated to parent elements.</p>
<pre><code class="language-plaintext">child.addEventListener('click', (e)=&gt;{
  e.stopPropagation()
  console.log(`I am from child || option false =&gt; bubbling phase`);  
})
</code></pre>
<h3>Output:</h3>
<pre><code class="language-plaintext">I am from child || option false =&gt; bubbling phase
</code></pre>
<h2>When to Use Bubbling (Default)</h2>
<ul>
<li><p>Implementing event delegation</p>
</li>
<li><p>Creating dropdowns that close when clicking outside</p>
</li>
<li><p>Most everyday event handling</p>
</li>
</ul>
<hr />
<h2>Capturing Phase (option: true)</h2>
<p>When we click on the target and keep the option <strong>true</strong>, the capturing phase is activated.<br />The event starts from the window and travels down to the target (top → bottom direction).</p>
<pre><code class="language-javascript">child.addEventListener('click', (e) =&gt; {
  console.log(`I am from Child || option true =&gt; capturing phase`);
}, true);

parent.addEventListener('click', (e) =&gt; {
  console.log(`I am from Parent || option true =&gt; capturing phase`);
}, true);

body.addEventListener('click', (e) =&gt; {
  console.log(`I am from Body || option true =&gt; capturing phase`);
}, true);
</code></pre>
<p>Output:</p>
<pre><code class="language-text">I am from Body || option true =&gt; capturing phase
I am from Parent || option true =&gt; capturing phase
I am from Child || option true =&gt; capturing phase
</code></pre>
<h2>Stop Capturing</h2>
<p>To stop the event from reaching the child, add <code>e.stopPropagation()</code> to the parent.<br />The event will stop at the parent.</p>
<pre><code class="language-plaintext">parent.addEventListener('click', (e)=&gt;{  
  e.stopPropagation()
  console.log(`I am from Parent || option true =&gt; capturing phase`);  
}, true)
</code></pre>
<h3>Output:</h3>
<pre><code class="language-plaintext">I am from Body || option true =&gt; capturing phase 
I am from Parent || option true =&gt; capturing phase
</code></pre>
<h2>When to Use Capturing</h2>
<ul>
<li><p>You need to intercept events before they reach children</p>
</li>
<li><p>Implementing global event logging/debugging</p>
</li>
<li><p>Creating security layers (blocking certain clicks)</p>
</li>
</ul>
<hr />
<h2>Stop Propagation Use Cases</h2>
<ul>
<li><p>Creating modals (click inside shouldn't close)</p>
</li>
<li><p>Implementing nested interactive elements</p>
</li>
<li><p>Preventing parent handlers from interfering</p>
</li>
</ul>
<hr />
<h2>stopPropagation vs stopImmediatePropagation</h2>
<h3>stopImmediatePropagation ensures:</h3>
<ol>
<li><p>No other handlers on the same element run</p>
</li>
<li><p>The event doesn't bubble to the parent</p>
</li>
</ol>
<p>Bigger problem:<br />What if multiple handlers are on the same element?</p>
<pre><code class="language-plaintext">// e.stopImmediatePropagation(); // Overkill - stops analytics too!
</code></pre>
<h2>Use stopPropagation() when:</h2>
<ul>
<li><p>Implementing modal close (click inside modal shouldn't close it)</p>
</li>
<li><p>Creating dropdown menus</p>
</li>
<li><p>Preventing parent handlers but keeping sibling handlers on the same element</p>
</li>
<li><p>Form validation where you still want analytics</p>
</li>
</ul>
<hr />
<h2>Use stopImmediatePropagation() when:</h2>
<ul>
<li><p>Emergency/critical operations that must run alone</p>
</li>
<li><p>Security-related checks that should block other handlers</p>
</li>
<li><p>When you absolutely need to prevent any other code from running for this event</p>
</li>
<li><p>Debugging (temporarily to isolate event handlers)</p>
</li>
</ul>
<hr />
<h2>Event Delegation</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/5900b3eb-071a-40c7-adbc-71cb4d4e7f25.png" alt="" style="display:block;margin:0 auto" />

<p>Event delegation is a technique where you attach a single event listener to a parent element instead of attaching multiple listeners to individual child elements.</p>
<p>The parent listens for events that bubble up from its children and handles them using <a href="http://event.target"><code>event.target</code></a>.</p>
<pre><code class="language-plaintext">&lt;ul id="todo-list"&gt;
  &lt;li&gt;Buy milk&lt;/li&gt;
  &lt;li&gt;Walk dog&lt;/li&gt;
  &lt;li&gt;Pay bills&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<pre><code class="language-plaintext">// Good: Single listener on parent
document.getElementById('todo-list').addEventListener('click', (event) =&gt; {
  // event.target is the actual element clicked
  console.log('Clicked:', event.target.textContent);
});
</code></pre>
<hr />
<h2>Benefits of Event Delegation</h2>
<ol>
<li><p>One listener for all items (current AND future)</p>
</li>
<li><p>Better performance</p>
</li>
<li><p>Automatically handles dynamically added elements</p>
</li>
</ol>
<hr />
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/21ad83af-a631-479b-b4ca-4314e28f431e.png" alt="" style="display:block;margin:0 auto" />

<p>Event delegation relies on event bubbling:</p>
<ol>
<li><p>You click a child element</p>
</li>
<li><p>The event bubbles up through ancestors</p>
</li>
<li><p>The parent's listener catches it</p>
</li>
<li><p>Use <a href="http://event.target"><code>event.target</code></a> to identify which child was clicked</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[The Problem - Traditional String Concatenation
Before template literals (introduced in ES6, 2015), building strings with dynamic content was clunky and error-prone. Developers had to use the + operato]]></description><link>https://blog.portfoliohub.in/template-literals-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/template-literals-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Thu, 19 Mar 2026 09:34:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/d439c67c-330b-41b3-9e50-6042f176efe3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3><strong>The Problem - Traditional String Concatenation</strong></h3>
<p>Before template literals (introduced in ES6, 2015), building strings with dynamic content was clunky and error-prone. Developers had to use the <code>+</code> operator to combine strings and variables.</p>
<pre><code class="language-plaintext">const name = "Alice";
const age = 30;

// Old way: Using + operator
const message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);
// Output: Hello, my name is Alice and I am 30 years old.
</code></pre>
<p><strong>Issues:</strong></p>
<ul>
<li><p>Hard to read with multiple variables</p>
</li>
<li><p>Tedious for multi-line strings</p>
</li>
<li><p>Error-prone with quotes and spacing</p>
</li>
</ul>
<h4><strong>The Multi-line Nightmare:</strong></h4>
<p>javascript</p>
<pre><code class="language-plaintext">const oldMultiLine = "This is line one.\n" +
" This is line two.\n" +
" This is line three.";
console.log(oldMultiLine);
// Output:
// This is line one.
// This is line two.
// This is line three.
</code></pre>
<p>This is messy, and the indentation looks awkward. You have to manually manage the line breaks and spaces.</p>
<h3><strong>The Solution - Template Literal Syntax</strong></h3>
<p>Template literals solve these problems with a simple syntax change: <strong>backticks (</strong><code>`</code><strong>)</strong> instead of quotes (<code>'</code> or <code>"</code>).</p>
<pre><code class="language-plaintext">// Old way with quotes
const oldWay = "I am a normal string";

// New way with template literals (backticks)
const newWay = `I am a template literal string`;

console.log(oldWay);
console.log(newWay);
</code></pre>
<p>That's it! Any string enclosed in backticks is a template literal. But the real power comes from what you can do inside them.</p>
<h3><strong>Embedding Variables and Expressions (String Interpolation)</strong></h3>
<p>The most important feature of template literals is <strong>string interpolation</strong>. Instead of using <code>+</code> to break the string apart, you use a placeholder: <code>${expression}</code>.</p>
<h4><strong>Basic Variable Embedding:</strong></h4>
<pre><code class="language-plaintext">const name = "Bob";
const age = 25;

// Template literal way - much cleaner!
const message = `Hello, my name is \({name} and I am \){age} years old.`;
console.log(message);
// Output: Hello, my name is Bob and I am 25 years old.
</code></pre>
<p>The ${} placeholder can contain any JavaScript expression, not just variable names. It will evaluate the expression and convert the result to a string.</p>
<pre><code class="language-plaintext">const a = 10; const b = 5;

// You can do math directly inside the placeholder console.log(The sum of \({a} and \){b} is ${a + b}.); // Output: The sum of 10 and 5 is 15.

// You can call methods const username = "Alice"; console.log(Your capitalized name is: ${username.toUpperCase()}); // Output: Your capitalized name is: ALICE

// You can even use ternary operators const price = 9.99; console.log(This item is ${price &gt; 10 ? 'expensive' : 'cheap'}.); // Output: This item is cheap.
</code></pre>
<p>This eliminates the need for temporary variables and makes the string-building logic inline and clear.</p>
<h3><strong>Multi-line Strings</strong></h3>
<p>This is where template literals truly shine. You can create multi-line strings simply by writing them across multiple lines in your code<br />javascript</p>
<pre><code class="language-plaintext">const multiLineMessage = `This is line one.
This is line two.
This is line three.`;

console.log(multiLineMessage);
// Output:
// This is line one.
// This is line two.
// This is line three.
</code></pre>
<h4><strong>Building HTML Snippet</strong></h4>
<pre><code class="language-plaintext">const itemName = "Coffee Mug";
const itemPrice = 12.99;

const htmlSnippet = `
&lt;div class="product-card"&gt;
    &lt;h3&gt;${itemName}&lt;/h3&gt;
    &lt;p class="price"&gt;$${itemPrice}&lt;/p&gt;
    &lt;button&gt;Add to Cart&lt;/button&gt;
&lt;/div&gt;
`;

console.log(htmlSnippet);
// Output: A nicely formatted, multi-line HTML string.
</code></pre>
<p>Template literals are a fundamental improvement in JavaScript that make working with strings cleaner, more intuitive, and less error-prone. They are a must-use feature in any modern codebase.</p>
]]></content:encoded></item><item><title><![CDATA[Callbacks in JavaScript]]></title><description><![CDATA[Functions as Values (The Foundation)
Before we talk about "callbacks," we need to understand that JavaScript treats functions as "first-class citizens." This means you can handle a function just like ]]></description><link>https://blog.portfoliohub.in/callbacks-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/callbacks-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Thu, 19 Mar 2026 09:10:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/c2a80c69-e3db-42fc-96de-bf7f86fc5763.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3><strong>Functions as Values (The Foundation)</strong></h3>
<p>Before we talk about "callbacks," we need to understand that JavaScript treats functions as "first-class citizens." This means you can handle a function just like any other piece of data.</p>
<p>You can:</p>
<ul>
<li><p>Store a function in a variable.</p>
</li>
<li><p>Store a function in an array or object.</p>
</li>
<li><p>Pass a function as an argument to another function.</p>
</li>
</ul>
<pre><code class="language-plaintext">// 1. Define a simple function (a "recipe" for an action)
function sayHello() {
    console.log("Hello there!");
}

// 2. Define another function that takes a function as an argument
function greeter( myFunction ) {
    console.log("About to run the passed function...");
    myFunction(); // 3. Call the function that was passed in
    console.log("Finished running the passed function.");
}

// 4. Pass 'sayHello' to 'greeter'. Notice we are NOT using parentheses 'sayHello()'.
//    We are passing the function itself, just like a variable.
greeter(sayHello);

// Output:
// About to run the passed function...
// Hello there!
// Finished running the passed function.
</code></pre>
<p>In this simple example, <code>sayHello</code> is a <strong>callback function</strong>. It's a function we "call back" later inside <code>greeter</code>.</p>
<h3><strong>What is a Callback Function?</strong></h3>
<p>A <strong>callback function</strong> is simply a function that is passed into another function as an argument. The "host" function can then <strong>execute (or "call back")</strong> the passed-in function at an appropriate time.</p>
<blockquote>
<p>Think of it like Ordering Pizza Delivery:</p>
<p>You call the pizza place and place your order.<br />They ask for your phone number—that’s the <strong>callback</strong>.<br />You go about your day (asynchronous waiting).<br />When the pizza is ready, they <strong>call you back</strong> to deliver it.</p>
</blockquote>
<p><strong>In JavaScript terms</strong>: You pass a function (your phone number) into another function (the pizza order system), and it gets executed later when the task is complete.</p>
<blockquote>
<p>Think of it like Laundry Service Pickup</p>
<ul>
<li><p>You schedule a laundry pickup and give them your address.</p>
</li>
<li><p>The laundry van comes, picks up your clothes, and leaves.</p>
</li>
<li><p>Later, when your laundry is done, they return it to your address.</p>
</li>
</ul>
</blockquote>
<p><strong>Your address is the callback</strong>—a way for the service to know where to respond once the task is complete.</p>
<p><strong>In JavaScript terms</strong>: You pass a function (your address) into another function (laundry service), and it gets called when the task (washing clothes) is finished.</p>
<h3><strong>Why Callbacks are Used in Asynchronous Programming</strong></h3>
<p>JavaScript is <strong>single-threaded</strong> and <strong>non-blocking</strong>. Callbacks allow:</p>
<ul>
<li><p>Reading a file from a hard drive.</p>
</li>
<li><p>Making a network request to an API.</p>
</li>
<li><p>Waiting for a timer (<code>setTimeout</code>).</p>
</li>
<li><p>Querying a database.</p>
</li>
</ul>
<h3>The Problem of Callback Nesting</h3>
<p><strong>When callbacks are nested deeply:</strong></p>
<pre><code class="language-plaintext">doTask1(() =&gt; {
  doTask2(() =&gt; {
    doTask3(() =&gt; {
      doTask4(() =&gt; {
        console.log("All tasks done");
      });
    });
  });
});



getUserData(function(userData) {
    console.log("Got user data. Now fetching friends...");
    
    getFriendsList(userData.id, function(friendsList) {
        console.log("Got friends list. Now fetching first friend's picture...");
        
        getProfilePicture(friendsList[0].id, function(pictureData) {
            console.log("Got picture data!");
            
            // Now we have everything, we can update the UI
            updateUI(userData, friendsList, pictureData);
            
        }); // End of getProfilePicture callback
        
    }); // End of getFriendsList callback
    
}); // End of getUserData callback
</code></pre>
<p>This leads to:</p>
<ol>
<li><p><strong>Difficult to Read:</strong></p>
</li>
<li><p><strong>Hard to Maintain:</strong></p>
</li>
<li><p><strong>Poor Error Handling:</strong></p>
</li>
<li><p><strong>Inversion of Control:</strong></p>
</li>
</ol>
<p><strong>Conceptual Fixes</strong>  </p>
<p>Use <strong>named functions</strong> to reduce nesting<br />Adopt <strong>Promises</strong> or <strong>async/await</strong> for cleaner flow<br />Modularize logic into smaller reusable pieces</p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in JavaScript]]></title><description><![CDATA[What nested arrays are ?
A nested array is a data structure where elements of an array can themselves be arrays.
Accessing Nested Arrays
const data = [10, 20, [30, 40]];

console.log(data[2]);      //]]></description><link>https://blog.portfoliohub.in/array-flatten-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/array-flatten-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 19:24:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/7e03cc9d-fb8f-4c75-a99f-c9695c759147.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What nested arrays are ?</h2>
<p>A nested array is a data structure where <strong>elements of an array can themselves be arrays</strong>.</p>
<p>Accessing Nested Arrays</p>
<pre><code class="language-plaintext">const data = [10, 20, [30, 40]];

console.log(data[2]);      // [30, 40]
console.log(data[2][0]);   // 30
console.log(data[2][1]);   // 40
</code></pre>
<h3>Why Use Nested Arrays?</h3>
<p>Represent <strong>matrix (2D arrays)</strong></p>
<ul>
<li><p>Store <strong>grouped data</strong></p>
</li>
<li><p>Useful in:</p>
<ul>
<li><p>Games (grid systems)</p>
</li>
<li><p>Tables / rows &amp; columns</p>
</li>
<li><p>Complex data structures</p>
</li>
</ul>
</li>
</ul>
<h3>Why flattening arrays is useful</h3>
<p>Flattening means converting a <strong>nested array</strong> (arrays within arrays) into a <strong>single-level array</strong>.</p>
<pre><code class="language-plaintext">const nested = [1, [2, [3, [4]]]];
const flat = nested.flat(Infinity); // [1, 2, 3, 4]
</code></pre>
<h3>Why Flattening Is Useful</h3>
<ul>
<li><p><strong>Simplifies data access</strong>: You can loop through or map over elements without checking for nested levels.</p>
</li>
<li><p><strong>Improves readability</strong>: Cleaner structure makes code easier to understand and maintain.</p>
</li>
<li><p><strong>Enables transformations</strong>: Useful when combining <code>.map()</code> and <code>.flat()</code> via <code>.flatMap()</code> for efficient data reshaping.</p>
</li>
<li><p><strong>Prepares data for APIs/UI</strong>: Many APIs return nested arrays; flattening helps normalize data for display or further processing.</p>
</li>
<li><p><strong>Reduces bugs</strong>: Avoids errors from unexpected nesting when performing operations like filtering or reducing.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/7d7dbafb-9dd6-4737-9641-38937c2503f2.png" alt="" style="display:block;margin:0 auto" />

<p>So instead of dealing with multiple levels, you get a single, straightforward list.</p>
<h3>Different approaches to flatten arrays</h3>
<p>1. <strong>Using</strong> <code>Array.prototype.flat()</code> <strong>(Modern &amp; Simple)</strong></p>
<pre><code class="language-plaintext">const arr = [1, [2, [3, [4]]]];
console.log(arr.flat(2));       // [1, 2, 3, [4]]
console.log(arr.flat(Infinity)); // [1, 2, 3, 4]
</code></pre>
<p>2. <strong>Using</strong> <code>Array.prototype.flatMap()</code> <strong>(Modern &amp; Simple)</strong><br />Combines mapping and flattening (only one level deep).</p>
<pre><code class="language-plaintext">const words = ["hello", "world"];
const chars = words.flatMap(word =&gt; word.split(""));
console.log(chars); // ["h","e","l","l","o","w","o","r","l","d"]
</code></pre>
<ul>
<li><strong>Best for</strong>: Transforming and flattening in one step</li>
</ul>
<p>3. <strong>Using</strong> for loop recursion</p>
<pre><code class="language-plaintext">function flattenArray(arr){
  if(!Array.isArray(arr) || arr.length === 0){
    return []
  }
  let resultArray = []
  for(let i =0; i&lt; arr.length; i++){
    let element = arr[i];
    if(Array.isArray(element)){
      resultArray = resultArray.concat(flatArray(element))
    }else{
      resultArray.push(element)
    }
  }
  return resultArray

}


console.log("flattenArray", (flattenArray([1, 2, [3, 4, 5, [6, [8]]]])));
</code></pre>
<p>4. <strong>Using</strong> reduce + concat</p>
<pre><code class="language-plaintext">function flattenArray(arr){
  if(!Array.isArray(arr) || arr.length === 0){
    return []
  }
  
  return arr.reduce((acc, curr)=&gt; {
    if(Array.isArray(curr)){
      return acc.concat(flattenArray(curr))
    }else{
      return acc.concat(curr)
    }
  },[])

}
</code></pre>
<p>5. <strong>Using</strong> without recursion</p>
<pre><code class="language-plaintext">function flattenArray(arr){
  if(!Array.isArray(arr) || arr.length === 0){
    return []
  }

  let stack = [...arr];
  let res = []

  while(stack.length){
    let cur = stack.pop();
    if(Array.isArray(cur)){
      stack.push(...cur)
    }else{
      res.push(cur)
    }
  }
  return res.reverse()
}
</code></pre>
<h3>Real-World Examples</h3>
<ul>
<li><p><strong>API responses</strong>: Cleaning nested JSON data before analysis.</p>
</li>
<li><p><strong>Form inputs</strong>: Flatten grouped values for validation.</p>
</li>
<li><p><strong>Data pipelines</strong>: Streamline mapping, filtering, and reducing.</p>
</li>
<li><p><strong>UI components</strong>: Render nested lists as flat menus or tables.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Modules: Import and Export Explained]]></title><description><![CDATA[In modern development—especially within the MERN stack—modules are the building blocks of your application. They allow you to split your code into separate files, making it manageable and professional]]></description><link>https://blog.portfoliohub.in/javascript-modules-import-and-export-explained</link><guid isPermaLink="true">https://blog.portfoliohub.in/javascript-modules-import-and-export-explained</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 17:04:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/42be53e4-3422-4732-a17a-1aff95427b3a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In modern development—especially within the <strong>MERN stack</strong>—modules are the building blocks of your application. They allow you to split your code into separate files, making it manageable and professional.</p>
<h2>Why modules are needed</h2>
<p>Before modules, all JavaScript code lived in one giant file or shared a single "global space." This caused two major problems:</p>
<ul>
<li><p><strong>Namespace Pollution:</strong> Two different scripts might use the same variable name (like <code>user</code>), causing one to overwrite the other.</p>
</li>
<li><p><strong>Maintainability:</strong> Finding a specific bug in a 5,000-line file is nearly impossible. Modules let you organize code by <strong>feature</strong> (e.g., <code>auth.js</code>, <code>api.js</code>).</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/5cade3af-ae89-4020-86a8-568fcce54632.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>Exporting functions or values</strong></h3>
<p>To make a piece of code available to the rest of your app, you must "publish" it using the <code>export</code> keyword.</p>
<pre><code class="language-plaintext">// math.js
export function add(a, b) {
  return a + b;
}

export const add = (a, b) =&gt; a + b;
export const multiply = (a, b) =&gt; a * b;

export const PI = 3.14;


// logger.js
export default function log(message) {
  console.log(message);
}
</code></pre>
<h3><strong>Importing modules</strong></h3>
<p>To use those functions in another file, you "request" them using the <code>import</code> keyword. You must provide the relative path to the file.</p>
<h4>Importing Named Exports</h4>
<pre><code class="language-plaintext">import { add, PI } from './math.js';
</code></pre>
<h4>Importing Default Export</h4>
<pre><code class="language-plaintext">import log from './logger.js';
</code></pre>
<p>You can also rename imports:</p>
<pre><code class="language-plaintext">import { add as sum } from './math.js';
</code></pre>
<h3>Default vs Named Exports</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Named Export</th>
<th>Default Export</th>
</tr>
</thead>
<tbody><tr>
<td>Syntax</td>
<td><code>export { name }</code></td>
<td><code>export default value</code></td>
</tr>
<tr>
<td>Import style</td>
<td><code>import { name } from '...'</code></td>
<td><code>import name from '...'</code></td>
</tr>
<tr>
<td>Multiple exports</td>
<td>✅ Yes</td>
<td>❌ Only one per module</td>
</tr>
<tr>
<td>Use case</td>
<td>Shared utilities, constants</td>
<td>Main function or class of a module</td>
</tr>
<tr>
<td>Naming</td>
<td>Must match the exported name.</td>
<td>Can be named anything you want.</td>
</tr>
</tbody></table>
<h3>Benefits of Modular Code</h3>
<ul>
<li><p><strong>Improved readability</strong>: Each module has a clear purpose.</p>
</li>
<li><p><strong>Better performance</strong>: Modern bundlers can optimize module loading.</p>
</li>
<li><p><strong>Scoped variables</strong>: Avoids polluting the global namespace.</p>
</li>
<li><p><strong>Team collaboration</strong>: Easier to assign and manage responsibilities</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Understanding Object-Oriented Programming in JavaScript]]></title><description><![CDATA[What Object-Oriented Programming (OOP) means?
Object-Oriented Programming (OOP) in JavaScript is used to organize code using objects, making the code more structured, reusable, and easier to maintain.]]></description><link>https://blog.portfoliohub.in/understanding-object-oriented-programming-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/understanding-object-oriented-programming-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 12:10:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/6737eeed-1a66-44a7-bf9e-fbf0cf4090c9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>What Object-Oriented Programming (OOP) means?</h3>
<p>Object-Oriented Programming (OOP) in JavaScript is used to organize code using objects, making the code more structured, reusable, and easier to maintain.</p>
<p>In large applications, writing everything as separate functions becomes messy. OOP allows you to group related data and functions together inside objects.</p>
<p>OOP allows us to control access to data.(Encapsulation)</p>
<p>OOP becomes useful when building large scalable systems, backend services, and complex frontend architectures.</p>
<p>JavaScript OOP is actually prototype-based and not class-based, even though we write classes</p>
<h3><strong>The "Syntactic Sugar" Reality</strong></h3>
<p><strong>The class is Syntactic Sugar of JS</strong><br />When you write class Person {} in JavaScript, the engine doesn't create a static class structure. Instead, it creates a function and attaches methods to its prototype property.</p>
<p>class Person {} console.log(typeof Person); // Output: "function"</p>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/211500ad-75cb-43b6-9700-374c38b10b9f.png" alt="" style="display:block;margin:0 auto" />

<p>A real-world analogy for OOP is a car factory Think of Class as a blueprint and Objects as actual cars built from that blueprint.</p>
<h3>What is a Class in JavaScript?</h3>
<p>A class is like a blueprint or design of a car.</p>
<p>The blueprint defines:</p>
<p>what properties the car will have<br />what actions the car can perform</p>
<pre><code class="language-javascript">class Car {
}
</code></pre>
<p>Here Car is a class that will be used to create car objects.</p>
<p><strong>Creating Objects Using Classes</strong><br />Objects are <strong>instances of a class</strong>.<br />We create objects using the <strong>new</strong> keyword.</p>
<pre><code class="language-plaintext">class Car {}

const car1 = new Car();
const car2 = new Car();
</code></pre>
<p><strong>Constructor Method</strong></p>
<p>A <strong>constructor</strong> is a special method that runs <strong>automatically when an object is created</strong>.</p>
<p>It is mainly used to <strong>initialize object properties</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">class Car {
  constructor(color, brand) {
    this.color = color;
    this.brand = brand;
  }
}

const car1 = new Car("Red", "Toyota");
</code></pre>
<p><code>constructor()</code> sets the initial values of the object.</p>
<p><strong>Methods Inside a Class</strong></p>
<p>Methods are <strong>functions defined inside a class</strong>.<br />They represent <strong>actions that objects can perform</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">class Car {
  constructor(color, brand) {
    this.color = color;
    this.brand = brand;
  }

  start() {
    console.log(this.brand + " car started");
  }

  stop() {
    console.log(this.brand + " car stopped");
  }
}

const car1 = new Car("Red", "Toyota");

car1.start();
</code></pre>
<p><strong>Basic Idea of Encapsulation</strong><br /><strong>Encapsulation</strong> means <strong>hiding internal data and controlling access to it</strong>.</p>
<p>Instead of directly modifying properties, we use <strong>methods to interact with the data</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">class BankAccount {
  #balance = 0;

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();

account.deposit(1000);
console.log(account.getBalance());
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>#balance</code> is <strong>private</strong></p>
</li>
<li><p>It cannot be accessed directly</p>
</li>
<li><p>it allow only using method<br />account.getBalance()</p>
</li>
</ul>
<p>So encapsulation helps to:</p>
<ul>
<li><p>protect data</p>
</li>
<li><p>control how data is used</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Operators: The Basics You Need to Know]]></title><description><![CDATA[1. Arithmetic Operators
let a = 10, b = 3;

// Basic arithmetic
console.log(a + b);   // 13 - Addition
console.log(a - b);   // 7  - Subtraction
console.log(a * b);   // 30 - Multiplication
console.lo]]></description><link>https://blog.portfoliohub.in/javascript-operators-the-basics-you-need-to-know</link><guid isPermaLink="true">https://blog.portfoliohub.in/javascript-operators-the-basics-you-need-to-know</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 12:00:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/02a07ad9-f1ec-4cbf-9b71-40c160c61763.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>1. Arithmetic Operators</strong></h2>
<pre><code class="language-plaintext">let a = 10, b = 3;

// Basic arithmetic
console.log(a + b);   // 13 - Addition
console.log(a - b);   // 7  - Subtraction
console.log(a * b);   // 30 - Multiplication
console.log(a / b);   // 3.333... - Division
console.log(a % b);   // 1  - Modulus (remainder)
</code></pre>
<h2><strong>2. Comparison Operators</strong></h2>
<pre><code class="language-plaintext">let a = 5, b = "5", c = 10;

// Equality
console.log(a == b);   // true - loose equality (compares value only)
console.log(a === b);  // false - strict equality (compares value AND type)

// Inequality
console.log(a != b);   // false - loose inequality
console.log(a !== b);  // true - strict inequality

// Relational
console.log(a &gt; c);    // false - greater than
console.log(a &lt; c);    // true - less than
console.log(a &gt;= 5);   // true - greater than or equal
console.log(a &lt;= 3);   // false - less than or equal

// Special comparisons
console.log(null == undefined);  // true
console.log(null === undefined); // false
console.log(NaN == NaN);         // false (NaN is not equal to anything)
console.log(isNaN(NaN));         // true - use isNaN() to check
</code></pre>
<h2><strong>3. Logical Operators</strong></h2>
<pre><code class="language-plaintext">let isLoggedIn = true;
let hasPermission = false;
let age = 25;

// AND (&amp;&amp;) - all conditions must be true
console.log(isLoggedIn &amp;&amp; hasPermission);     // false
console.log(isLoggedIn &amp;&amp; age &gt; 18);          // true

// OR (||) - at least one condition must be true
console.log(isLoggedIn || hasPermission);      // true
console.log(hasPermission || age &lt; 18);        // false

// NOT (!) - inverts the boolean value
console.log(!isLoggedIn);                      // false
console.log(!hasPermission);                    // true

// Short-circuit evaluation
let user = null;
let defaultName = "Guest";

// Returns first truthy value
let name = user || defaultName;
console.log(name);  // "Guest"
</code></pre>
<h2><strong>4. Assignment Operators</strong></h2>
<pre><code class="language-plaintext">let x = 10;  // Basic assignment

// Compound assignment
x += 5;      // x = x + 5 -&gt; 15
console.log(x);

x -= 3;      // x = x - 3 -&gt; 12
console.log(x);

x *= 2;      // x = x * 2 -&gt; 24
console.log(x);

x /= 4;      // x = x / 4 -&gt; 6
console.log(x);

x %= 4;      // x = x % 4 -&gt; 2
console.log(x);

x **= 3;     // x = x ** 3 -&gt; 8 (exponentiation)
console.log(x);

// Bitwise assignment (less common)
let y = 5;   // binary: 0101
y &amp;= 3;      // y = y &amp; 3 -&gt; 1 (binary: 0001)
console.log(y);

// Logical assignment (ES12)
let a = null;
a ||= 10;    // a = a || 10 -&gt; 10 (assigns if falsy)
console.log(a);

let b = 5;
b &amp;&amp;= 3;     // b = b &amp;&amp; 3 -&gt; 3 (assigns if truthy)
console.log(b);

let c = null;
c ??= 20;    // c = c ?? 20 -&gt; 20 (assigns if null/undefined)
console.log(c);
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Demystifying this, call(), apply(), and bind() in JavaScript]]></title><description><![CDATA['this'The first thing that defines JavaScript is how it uses this.

this doesn't exist in other languages at the same level or in the same way it exists in JS.JavaScript makes itself unique (and trick]]></description><link>https://blog.portfoliohub.in/demystifying-this-call-apply-and-bind-in-javascript</link><guid isPermaLink="true">https://blog.portfoliohub.in/demystifying-this-call-apply-and-bind-in-javascript</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 11:52:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/ce9f3660-9857-4130-bc4d-72818d2b2344.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>'this'</strong><br />The first thing that defines JavaScript is how it uses <strong>this</strong>.</p>
</blockquote>
<p><strong>this</strong> doesn't exist in other languages at the same level or in the same way it exists in JS.<br />JavaScript makes itself unique (and tricky) by <strong>this</strong>.</p>
<p>When we check the position of <strong>this</strong> in the browser</p>
<pre><code class="language-plaintext">console.log(this)
</code></pre>
<p>We will <strong>receive</strong> the window object.</p>
<p>Run in the Node environment</p>
<pre><code class="language-plaintext">console.log("this ===&gt;", this)
</code></pre>
<p>We will <strong>receive</strong></p>
<p><code>this ===&gt; {}</code></p>
<p><strong>Its use depends on the context.</strong></p>
<p>When we run the below function in Node</p>
<p><code>node script.js</code></p>
<pre><code class="language-plaintext">function ranveerOnGlobalStage() {
  return typeof this;
}
console.log("ranveerOnGlobalStage ==&gt;", ranveerOnGlobalStage());
</code></pre>
<p>we will get</p>
<p><strong>ranveerOnGlobalStage ==&gt; undefined</strong></p>
<p>because Node.js wraps every file inside a function internally and <strong>global</strong> is Node.js-specific.</p>
<p>If a function is not running in the global environment or it is in functional scope, at that time you will get <code>typeof undefined</code> instead of <code>Object</code>.</p>
<p>It means the function is not running in the real global scope or Node has enabled <code>"use strict"</code> mode by default.</p>
<p>Now interestingly you can make it global stage by using the <strong>call</strong> method.</p>
<pre><code class="language-plaintext">console.log(ranveerOnGlobalStage.call(global));
</code></pre>
<p>Now you will return the <strong>global object</strong> of Node.</p>
<pre><code class="language-plaintext">function ranveerOnGlobalStage() {
  return typeof this;
}
console.log("ranveerOnGlobalStage ==&gt;", ranveerOnGlobalStage.call(global));
</code></pre>
<p>we will get</p>
<pre><code class="language-plaintext">ranveerOnGlobalStage ==&gt; object
</code></pre>
<p>How <strong>global</strong> and <strong>globalThis</strong> work you can check my link below</p>
<p><a href="https://node-js.hashnode.dev/understanding-global-vs-globalthis-in-javascript-and-node-js">https://node-js.hashnode.dev/understanding-global-vs-globalthis-in-javascript-and-node-js</a></p>
<pre><code class="language-plaintext">function ranveerWithNoScript() {
  return this;
}
console.log(ranveerWithNoScript()); // =&gt; return undefined
console.log(ranveerWithNoScript.call(global));
</code></pre>
<p>return <code>&lt;ref *1&gt; Object [global] { global: [Circular *1], .....</code></p>
<p>What will <strong>output</strong> in the below function?</p>
<p>Guess where <strong>this</strong> is pointing.</p>
<p>If we run the code below</p>
<pre><code class="language-plaintext">const bollywoodFilm2 = {
  name: "Dhurandhar",
  lead: "Ranveer",
  
  introduce() {
    return `\({this.lead} performs in \){this.name}`;
  },
};
</code></pre>
<pre><code class="language-plaintext">console.log(bollywoodFilm2.introduce());
</code></pre>
<p>we will get</p>
<p><strong>Ranveer performs in Dhurandhar</strong></p>
<p>because here <strong>this context is available</strong>.</p>
<p>What can we expect <strong>this</strong> in the below function?</p>
<p>This is an <strong>arrow function</strong>.</p>
<pre><code class="language-plaintext">const filmDirector = {
  name: "Sanjay Leela Bhansali",
  cast: ["Ranveer", "Deepika", "Priyanka"],

  announceCast() {
   this.cast
    .forEach((actor) =&gt; {
      console.log(`\({this.name} introduces \){actor}`);
    });
  },
};

filmDirector.announceCast()
</code></pre>
<p>What we observe is that the arrow function has printed <strong>this</strong>.</p>
<p>Normally arrow functions don't support <strong>this</strong> in the global environment, but here:</p>
<p>Arrow functions don't have their own <strong>this</strong> binding.</p>
<p>They inherit <strong>this</strong> from the surrounding (lexical) scope.</p>
<pre><code class="language-plaintext">Sanjay Leela Bhansali introduces Ranveer
Sanjay Leela Bhansali introduces Deepika
Sanjay Leela Bhansali introduces Priyanka
</code></pre>
<p>If you want to know about arrow functions, you can check out my blog link on arrow functions</p>
<p><a href="https://js-functions.hashnode.dev/">https://js-functions.hashnode.dev/</a></p>
<p>How can we expect the output in the below function with a nested arrow function?</p>
<pre><code class="language-plaintext">const filmSet = {
  crew: "Spot boys",
  prepareProps() {
    console.log(`Outer this.crew: ${this.crew}`);

    const arrangeLights = () =&gt; {
      console.log(`Arrow this.crew: ${this.crew}`);
    };
    arrangeLights();
  },
};

filmSet.prepareProps();
</code></pre>
<pre><code class="language-plaintext">Outer this.crew: Spot boys
Arrow this.crew: Spot boys
</code></pre>
<p>because <strong>this context is available</strong>, we receive the result.</p>
<p>They inherit <strong>this</strong> from the surrounding (lexical) scope.</p>
<p>What can we expect the result from the regular nested function?</p>
<pre><code class="language-plaintext">const filmSet4 = {
  crew: "Spot boys",
  prepareProps() {
    console.log(`Outer this.crew: ${this.crew}`);

    function arrangeChairs() {
      console.log(`Inner this.crew: ${this.crew}`);
    }
    arrangeChairs();
  },
};

filmSet4.prepareProps();
</code></pre>
<p>Here we are calling the nested function without <strong>this context</strong> and defining it as a standalone method.</p>
<p>It's JavaScript behavior that here we <strong>lose the this context</strong> and get <strong>undefined</strong>.</p>
<pre><code class="language-plaintext">arrangeChairs();
</code></pre>
<p>How can we <strong>fix</strong> it?</p>
<pre><code class="language-plaintext">const filmSet5 = {
  crew: "Spot boys",
  prepareProps() {
    console.log(`Outer this.crew: ${this.crew}`);

    function arrangeChairs() {
      console.log(`Inner this.crew: ${this.crew}`);
    }
    arrangeChairs.bind(this);
  },
};

filmSet5.prepareProps();
</code></pre>
<p>The same function behaves differently based on <strong>how it's called</strong>:</p>
<pre><code class="language-plaintext">function greet() {
  return console.log(`Hello, I'm ${this.name}`);
}

const person = { name: "Advait", greet };

console.log(person.greet()); 
console.log(greet.call(person1)); 
console.log(greet.apply(person1));
</code></pre>
<p>This is why JavaScript is said to have <strong>dynamic this binding</strong> — the value of <strong>this</strong> is determined at call-time, not at definition-time.</p>
<p>Now check the regular function without nested</p>
<pre><code class="language-plaintext">function greet() {
  return console.log(`Hello, I'm ${this.name}`);
}

const person1 = { name: "Advait", greet };

// Hello, I'm Advait
console.log(person1.greet());
console.log(greet.call(person1));
</code></pre>
<p>And check the arrow function without nested in the global state</p>
<pre><code class="language-plaintext">const greet = () =&gt; {
  console.log(`Hello, I'm Arrow function ${this.name}`);
};

const person2 = { name: "Alice", greet };
person2.greet();

// Hello, I'm Arrow function undefined
</code></pre>
<p>Not receiving the <strong>this context</strong>, it inherits <strong>this</strong> from the surrounding (lexical) scope.</p>
<p>Another classic JavaScript <strong>this binding pitfall</strong></p>
<pre><code class="language-plaintext">const actor = {
  name: "Ranveer",
  bow() {
    return `${this.name} takes a bow`;
  },
};

const detachedBow = actor.bow;
console.log(detachedBow());
</code></pre>
<p>Functions in JS are <strong>first-class citizens</strong>.</p>
<p><code>actor.bow</code> is a reference to the function, not copying the object.</p>
<p>When called as <code>actor.bow()</code>, the object before the dot sets <strong>this</strong>.</p>
<p>When assigned to a variable and called directly, there's no object before the dot, so <strong>this</strong> defaults to <strong>global/undefined</strong>.</p>
<p>Solution</p>
<pre><code class="language-plaintext">const boundBow = actor.bow.bind(actor);
</code></pre>
<hr />
<h3>Conclusion behaviour of JS</h3>
<p>Regular function has its own <strong>this</strong> in the global state.</p>
<p>It depends purely on <strong>HOW the function is called</strong>.</p>
<p>But they <strong>don't have this in nested functions</strong> until you set it using the <code>.call</code> method.</p>
<p>It doesn't have variable access there. In detached methods also it doesn't have variable access there.</p>
<p>Arrow functions <strong>don't have their own this</strong> in the global state.</p>
<p>They don't have variable access there, but in nested functions they <strong>capture the outer scope this</strong>.</p>
<p>They take the reference of the variable.</p>
<p>Regular function: <strong>this is dynamic (call-site based), creates new memory</strong></p>
<p>Arrow function: <strong>this is lexical (scope based)</strong></p>
<hr />
<h3>Behind the scene</h3>
<p>When JS runs code, it creates:</p>
<ol>
<li><p><strong>Lexical Environment (Scope / Variables Memory)</strong></p>
</li>
<li><p><strong>Execution Context (Includes this)</strong></p>
</li>
</ol>
<p><strong>this is NOT part of the normal variable scope.</strong></p>
<p>It lives in the <strong>Execution Context</strong>, not inside the lexical variable environment.</p>
<h3>The Core Purpose of <code>call</code>, <code>apply</code>, and <code>bind.</code></h3>
<p><code>call</code>, <code>apply</code>, and <code>bind</code> allow you to <strong>explicitly</strong> define what <code>this</code> should refer to, regardless of the calling context.</p>
<p><strong>1.</strong> <code>call()</code></p>
<p>The <code>call()</code> method invokes a function immediately.</p>
<pre><code class="language-javascript">function cookDish(ingredient, style){
    return `\({this.name} prepares \){ingredient} in ${style} style !`
}

const guptaKitchen = {name : "Gupta jis kitchen"}

console.log(cookDish.call(guptaKitchen,"Panner bhrju", "Novaeg"));
</code></pre>
<h3><strong>2.</strong> <code>apply()</code></h3>
<p>The <code>apply()</code> method is almost identical to <code>call()</code>, but instead of passing arguments individually, you pass them as a single <strong>array</strong>.</p>
<pre><code class="language-javascript">function cookDish(ingredient, style){
    return `\({this.name} prepares \){ingredient} in ${style} style !`
}

const guptaOrder = ["Chole kulche", "Punjabi Dhaba"]

console.log(cookDish.apply(guptaKitchen, guptaOrder));

const bills = [100, 30, 45, 50];
console.log(Math.max.apply(null, bills))
</code></pre>
<h3>3. <code>bind()</code></h3>
<p>Unlike the other two, <code>bind()</code> <strong>does not</strong> execute the function immediately. Instead, it returns a new copy of the function with the <code>this</code> value permanently set to the provided object.</p>
<pre><code class="language-javascript">function reportDelivery(location, status){
    return `\({this.name} at \){location}: ${status}`;
}
const deliveryBoy = { name: "Ranveer" };

console.log("Call", reportDelivery.call(deliveryBoy, "Mumbai", "Order"))
console.log("apply", reportDelivery.call(deliveryBoy, ["Moon", "Pending"]))
console.log("Bind", reportDelivery.bind(deliveryBoy, ("Haridwar", "What")))

const bindReport = reportDelivery.bind(deliveryBoy)
console.log(bindReport("Haridwar", "What"));
</code></pre>
<h3>More than The Core Purpose of this binding</h3>
<h3><strong>1.Function Borrowing</strong></h3>
<pre><code class="language-javascript">const calculator = {
  value: 0,
  add(num) { this.value += num; return this; },
  subtract(num) { this.value -= num; return this; }
};

const otherCalc = { value: 10 };

// Borrow methods from calculator
calculator.add.call(otherCalc, 5);
calculator.subtract.apply(otherCalc, [3]);
console.log(otherCalc.value); // 12

// Borrow array methods for array-like objects
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const realArray = Array.prototype.slice.call(arrayLike);
console.log(realArray); // ['a', 'b']
</code></pre>
<h3>**2.**Partial Application (Currying)</h3>
<pre><code class="language-javascript">function multiply(x, y, z) {
  return x * y * z;
}

// Create specialized functions
const multiplyByTwo = multiply.bind(null, 2);
const multiplyByTwoAndThree = multiply.bind(null, 2, 3);

console.log(multiplyByTwo(4, 5));     // 2 * 4 * 5 = 40
console.log(multiplyByTwoAndThree(5)); // 2 * 3 * 5 = 30
</code></pre>
<p><strong>3.</strong> Function Composition</p>
<pre><code class="language-javascript">function compose(...functions) {
  return functions.reduce((f, g) =&gt; 
    (...args) =&gt; f.call(null, g.apply(null, args))
  );
}

const addOne = x =&gt; x + 1;
const double = x =&gt; x * 2;
const square = x =&gt; x * x;

const composed = compose(addOne, double, square);
console.log(composed(3)); // square(3) = 9, double(9) = 18, addOne(18) = 19
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Function in JS]]></title><description><![CDATA[A function is a reusable set of instructions.It is a block of code designed to perform a specific action.
In JavaScript, functions are first-class citizens, which means they can be:

stored in variabl]]></description><link>https://blog.portfoliohub.in/function-in-js</link><guid isPermaLink="true">https://blog.portfoliohub.in/function-in-js</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 11:36:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/1c03639c-4ac9-4ec0-9035-5ffb7ad6d716.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A <strong>function</strong> is a reusable set of instructions.<br />It is a <strong>block of code designed to perform a specific action</strong>.</p>
<p>In JavaScript, <strong>functions are first-class citizens</strong>, which means they can be:</p>
<ul>
<li><p>stored in variables</p>
</li>
<li><p>passed as arguments</p>
</li>
<li><p>returned from other functions</p>
</li>
</ul>
<hr />
<h2>Function Declaration</h2>
<p>When we write a function <strong>with a function name</strong>, it is called a <strong>function declaration</strong>.</p>
<p>Function declarations are <strong>fully hoisted in memory</strong>, so they can be used <strong>before their declaration in the code</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function greet(name) {
    return `Hello, ${name}!`;
}
</code></pre>
<p>Anonymous functions <strong>cannot be used directly in function declarations</strong>.</p>
<p>Example of an anonymous function:</p>
<pre><code class="language-plaintext">function() {}
</code></pre>
<p>This will <strong>not work as a function declaration</strong> because it has no name.</p>
<hr />
<h2>Function Expression</h2>
<p>When we <strong>assign a function to a variable</strong>, it is called a <strong>function expression</strong>.</p>
<p>Function expressions are <strong>not fully hoisted</strong>, so they <strong>cannot be used before they are defined</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const greet = function(name) {
    return `Hello, ${name}!`;
};
</code></pre>
<p>A function expression <strong>can be an anonymous function</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const anonymous = function() {};
</code></pre>
<p>It can also be a <strong>named function expression</strong>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const named = function func() {};
</code></pre>
<hr />
<h2>Hoisting Difference</h2>
<p>We can see the difference using the following examples.</p>
<h3>Function Declaration (Works)</h3>
<pre><code class="language-plaintext">sayHello("John"); // "Hello, John!"

function sayHello(name) {
    return `Hello, ${name}!`;
}
</code></pre>
<h3>Function Expression (Error)</h3>
<pre><code class="language-plaintext">sayHi("John"); // ReferenceError: Cannot access before initialization

const sayHi = function(name) {
    return `Hi, ${name}!`;
};
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/cbdf7d36-0469-40c9-9be5-21a4886b26a9.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[Arrow functions]]></title><description><![CDATA[What are arrow functions?
Arrow functions is another very simple and concise syntax for creating functions,that’s often better than Function Expressions and is written: a() => {},
where => is called t]]></description><link>https://blog.portfoliohub.in/arrow-functions</link><guid isPermaLink="true">https://blog.portfoliohub.in/arrow-functions</guid><dc:creator><![CDATA[Ravindra Dhadave]]></dc:creator><pubDate>Wed, 18 Mar 2026 11:22:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6951f0fa71561c01e2f304ee/2b872a59-e3c0-42f5-9d2f-9c889d6f783c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>What are arrow functions?</h1>
<p>Arrow functions is another very simple and concise syntax for creating functions,<br />that’s often better than Function Expressions and is written: a<br /><code>()</code> =&gt; <code>{}</code>,</p>
<p>where <code>=&gt;</code> is called the fat-arrow or just arrow.</p>
<p>In arrow function must be<br />1.declare after initialize (Call after definition)<br />2.Arrow functions work great as callbacks:, in setTimeout,forEach, map, filter reduce ...</p>
<p>When we defined using curley brace it explicitly return</p>
<pre><code class="language-plaintext">const square = x =&gt; {
  return x * x;
};
// Two parameters
const add = (a, b) =&gt; {
  return a + b;
};
// Three parameters
const calculate = (x, y, z) =&gt; {
  return (x + y) * z;
};
</code></pre>
<p>when we are not used the curley brace in arrow funtion it implicitly return</p>
<pre><code class="language-plaintext">const square = x =&gt; x * x;
const add = (a, b) =&gt; a + b;
const sum = (...args) =&gt; args.reduce((a, b) =&gt; a + b, 0);
sum(1, 2, 3); // 6

// Trying to use arguments inside arrow throws ReferenceError
const noArgs = () =&gt; console.log(arguments); // ReferenceError
</code></pre>
<p>what are difference between arrow function and normal function?</p>
<p>Arrow Function<br />1.Does not have its own this. It inherits this from the surrounding (lexical) scope where it is defined.</p>
<p>2.The value of this inside an arrow function is fixed and cannot be changed by .call(), .apply(), or .bind().</p>
<p>3.Does not have its own arguments object. If you need access to arguments, you must use rest parameters or rely on the enclosing function's arguments.</p>
<p>4.Cannot be used as a constructor. Trying to use new with an arrow function throws an error..</p>
]]></content:encoded></item></channel></rss>