<?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[Satpalsinh Rana]]></title><description><![CDATA[I am a software engineer who loves coding and Tea.]]></description><link>https://blogs.satpal.cloud</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1767287274080/f383494b-5b32-483c-b5b4-729b5b67cdd9.png</url><title>Satpalsinh Rana</title><link>https://blogs.satpal.cloud</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 24 Apr 2026 22:54:58 GMT</lastBuildDate><atom:link href="https://blogs.satpal.cloud/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[NodeJS ]]></title><description><![CDATA[Why Did Node.js Even Need to Exist?
You already know JavaScript. You know it runs in the browser. The entire purpose was simple make web pages respond to user actions. But have you ever think why does]]></description><link>https://blogs.satpal.cloud/nodejs</link><guid isPermaLink="true">https://blogs.satpal.cloud/nodejs</guid><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Mon, 20 Apr 2026 16:31:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/c79a459b-12fc-418b-a0a9-3a38ad0d6c07.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Why Did Node.js Even Need to Exist?</h2>
<p>You already know JavaScript. You know it runs in the browser. The entire purpose was simple make web pages respond to user actions. But have you ever think why does it run in the browser at all?</p>
<p>Because something inside the browser is reading your JavaScript line by line and telling the computer what to do. That something is called a runtime engine. In Chrome, it's called V8. In Firefox, it's SpiderMonkey. Think of it as a translator JavaScript speaks, the engine listens, and the computer acts.</p>
<p>Now here's the problem. That translator only lived inside the browser. You couldn't take it outside. You couldn't run JavaScript on a server, talk to a database, read files on disk, or build an API. JavaScript was essentially trapped.</p>
<p><strong>Ryan Dahl</strong> looked at this in 2009 and said what if we break it out? He took V8 out of Chrome and wrapped it with something extra. That wrapper became Node.js.</p>
<h2>How Nodejs was build?</h2>
<p><strong>Ryan</strong> noticed that Google's V8 engine inside Chrome was fast, open-source, and not tied to the browser in any fundamental way. It was just a C++ library that could compile and execute JavaScript. So he pulled it out.</p>
<p>But V8 alone was only half the answer. He needed to give it hands. He wrapped V8 with a C library called <strong>libuv</strong>, which was built specifically to handle I/O operations file system calls, network connections, DNS lookups across different operating systems in a non-blocking way.</p>
<p>That combination is the entire foundation of Node.js.</p>
<h2>V8</h2>
<p>You don't need to understand V8 deeply to use Node.js. But a high-level picture helps.</p>
<p>V8 job is to take JavaScript code and turn it into something the CPU can actually. V8 reads your code, figures out what it's doing, and translates it into native machine code on the fly. This is called JIT(Just in time) compilation.</p>
<p>The result is that JavaScript runs fast compared to what anyone expected from a scripting language. V8 also handles memory management for you allocating it when you create objects, cleaning it up when you're done with them, through a process called garbage collection.</p>
<p>When Node.js runs your code, V8 is the one actually executing it. Node.js just sets the stage.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/402fffe2-9f89-4840-bd35-ec577f053589.png" alt="" style="display:block;margin:0 auto" />

<h2>Event Drive Architecture</h2>
<p>Let's use an analogy. Imagine a restaurant.</p>
<p>Traditional servers like PHP or Java with thread-per-request models work like a waiter who takes your order and then stands next to your table, doing absolutely nothing, until your food comes out of the kitchen. During that entire waiting time, that waiter is occupied. If 1,000 customers walk in, you need 1,000 waiters just standing around.</p>
<p>Node.js works like a smart waiter. They take your order, walk it to the kitchen, and immediately go take the next table's order. When the kitchen shouts "order up!", the waiter gets notified and delivers it. One waiter can handle 100 tables because they're never standing around waiting.</p>
<p>That's event-driven, non-blocking I/O. Instead of stopping everything while waiting for a database response or a file read, Node.js registers a callback and moves on. When the result is ready, it comes back via the event loop.</p>
<p>This is the reason Node.js can handle tens of thousands of concurrent connections on a single server process while traditional multi-threaded servers would be crushed under that load. Not because Node.js is faster at computation it's often not. But because it never idles.</p>
<p>Now here's how the Node.js runtime architecture actually fits together:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/a76a497a-4970-4426-b950-97a8f59b00e7.png" alt="" style="display:block;margin:0 auto" />

<h2>General use cases</h2>
<ul>
<li><p>REST APIs and GraphQL Backends</p>
</li>
<li><p>Streaming applications</p>
</li>
<li><p>Serverless functions</p>
</li>
<li><p>Internet of Things (IoT)</p>
</li>
</ul>
<p>I hope you get to know something valuable from the article.</p>
<p>I’m currently deep-diving into the <strong>JavaScript</strong>, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!</p>
<ul>
<li><p><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/satpalsinhrana"><strong>Satpalsinh's Profile</strong></a></p>
</li>
<li><p><strong>Follow my Blog:</strong> <a href="http://blogs.satpal.cloud"><strong>blogs.satpal.cloud</strong></a></p>
</li>
</ul>
<p><strong>Keep coding and keep building.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in JavaScript]]></title><description><![CDATA[What Exactly Are Nested Arrays?
A nested array (or a multi-dimensional array) is simply an array that contains other arrays as its elements.
Think of a standard array as a single-story egg carton. A n]]></description><link>https://blogs.satpal.cloud/array-flatten-in-javascript</link><guid isPermaLink="true">https://blogs.satpal.cloud/array-flatten-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 26 Mar 2026 17:09:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f25b597d-e56b-4c7a-b7ec-0e53942fe6de.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What Exactly Are Nested Arrays?</h2>
<p>A nested array (or a multi-dimensional array) is simply an array that contains other arrays as its elements.</p>
<p>Think of a standard array as a single-story egg carton. A nested array is more like a shipping crate filled with smaller boxes, some of which might contain even smaller boxes.</p>
<p><strong>Example:</strong> <code>const nested = [1, [2, 3], [[4, 5], 6]];</code></p>
<p>In the example above, <code>1</code> is at the top level, but <code>4</code> and <code>5</code> are buried three levels deep.</p>
<h2>Why Bother Flattening?</h2>
<p>Flattening is the process of reducing the dimensionality of an array. We do this because:</p>
<ul>
<li><p><strong>Easier Iteration:</strong> It’s much simpler to run a single <code>.map()</code> or <code>.forEach()</code> on a flat list than to write recursive loops for every level.</p>
</li>
<li><p><strong>Data Consistency:</strong> Many UI components (like dropdowns or tables) expect a simple, linear array of items.</p>
</li>
<li><p><strong>Searchability:</strong> Finding a specific value is faster when you don't have to check every "sub-box."</p>
</li>
</ul>
<h2>Transformation</h2>
<p>When we "flatten," we are essentially taking every element from the inner arrays and pushing them into a new, single-level array while maintaining their original order.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2f971932-454f-4e49-aa7e-3032577f7046.png" alt="" style="display:block;margin:0 auto" />

<h3>How to Flatten Arrays:</h3>
<h2><code>flat()</code></h2>
<p>Introduced in ES2019, the <code>.flat()</code> method is the gold standard. By default, it flattens one level deep, but you can pass a depth or use <code>Infinity</code> to go all the way.</p>
<pre><code class="language-javascript">const multidimensional = [1, [2, [3, [4]]]];

console.log(multidimensional.flat()); // [1, 2, [3, [4]]]

console.log(multidimensional.flat(Infinity)); // [1, 2, 3, 4]
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ddb27ef8-5524-4391-afc6-c440c69a4b8d.png" alt="" style="display:block;margin:0 auto" />

<h2><code>reduce()</code> and <code>concat()</code></h2>
<p>Before <code>.flat()</code> existed, this was the go-to manual method. It helps you understand the <strong>logic</strong> of the transformation: "Take the accumulator, and merge it with the current item."</p>
<pre><code class="language-javascript">const nested = [1, [2, 3], [4]];
const flat = nested.reduce((acc, val) =&gt; acc.concat(val), []);
</code></pre>
<h2><code>toString()</code> and <code>split()</code></h2>
<p>If your array only contains numbers or strings, you can convert the whole thing to a string (which removes brackets) and then split it back.</p>
<p>Note: Use this with caution, as it turns everything into strings!</p>
<p>When you see a nested structure, just ask yourself about the <strong>depth</strong>.</p>
<ul>
<li><p>Is it always one level deep? Use <code>[].concat(...arr)</code>.</p>
</li>
<li><p>Is the depth unknown? Use <code>.flat(Infinity)</code>.</p>
</li>
<li><p>Are you on an older environment (like legacy IE)? You'll need a recursive polyfill.</p>
</li>
</ul>
<p>Flattening isn't just about making arrays shorter; it’s about making your data <strong>usable</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript]]></title><description><![CDATA[Every program makes assumptions. It assumes the network is available. It assumes the user gave you a valid input. It assumes the file exists. It assumes the API response has the shape you expect.
Most]]></description><link>https://blogs.satpal.cloud/error-handling-in-javascript</link><guid isPermaLink="true">https://blogs.satpal.cloud/error-handling-in-javascript</guid><category><![CDATA[error handling]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 26 Mar 2026 16:55:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/80978952-1e64-46ca-aefd-e1b169ace0ce.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every program makes assumptions. It assumes the network is available. It assumes the user gave you a valid input. It assumes the file exists. It assumes the API response has the shape you expect.</p>
<p>Most of the time those assumptions hold. Then they don't and what happens next is entirely up to you.</p>
<p>JavaScript gives you a system for managing failures without letting them crash the whole program. Understanding it isn't just about catching errors. It's about writing code that fails gracefully code that tells you exactly what went wrong, cleans up after itself, and gives the user something useful instead of a blank screen or a frozen UI.</p>
<h2>What errors actually are in JavaScript</h2>
<p>When JavaScript encounters something it can't handle dividing by something illegal, calling a method on <code>undefined</code>, trying to parse malformed JSON it creates an <code>Error</code> object and throws it. This throw unwinds the call stack, skipping everything below it, until something catches it or it reaches the top level and crashes your program.</p>
<pre><code class="language-javascript">const user = null;
console.log(user.name); // TypeError: Cannot read properties of null
</code></pre>
<p>That <code>TypeError</code> is a real object. It has a <code>message</code> (what went wrong), a <code>name</code> (the type of error), and a <code>stack</code> (the trace of function calls that led here). JavaScript creates it, throws it, and your program stops unless something is listening for it.</p>
<p>JavaScript has several built-in error types:</p>
<ul>
<li><p><code>TypeError</code> (wrong type)</p>
</li>
<li><p><code>ReferenceError</code> (variable doesn't exist)</p>
</li>
<li><p><code>SyntaxError</code> (invalid code)</p>
</li>
<li><p><code>RangeError</code> (value out of bounds).</p>
</li>
</ul>
<p>They all inherit from the base <code>Error</code> class.</p>
<h2>The <code>try/catch</code> block</h2>
<p><code>try/catch</code> lets you put risky code in a guarded zone. If anything throws inside <code>try</code>, execution jumps immediately to <code>catch</code> and you decide what to do with the error instead of letting it crash your program.</p>
<pre><code class="language-javascript">try {
  const data = JSON.parse("this is not valid json");
  console.log(data);
} catch (error) {
  console.error("Failed to parse:", error.message);
}

// Failed to parse: Unexpected token 'h', "this is n"... is not valid JSON
</code></pre>
<p>Without <code>try/catch</code>, that <code>JSON.parse</code> throws a <code>SyntaxError</code> and everything stops. With it, you catch the error, log it clearly, and your program keeps running.</p>
<p>The <code>error</code> object passed to <code>catch</code> is whatever was thrown. It has two properties you'll use constantly:</p>
<pre><code class="language-javascript">try {
  undeclaredVariable;
} catch (error) {
  console.log(error.name);    // "ReferenceError"
  console.log(error.message); // "undeclaredVariable is not defined"
}
</code></pre>
<h2>The <code>finally</code> block</h2>
<p><code>finally</code> is a block that runs no matter what whether the <code>try</code> succeeded, whether the <code>catch</code> triggered, whether an error was re-thrown. It always runs.</p>
<pre><code class="language-javascript">function loadData() {
  showSpinner();

  try {
    const result = fetchSomething();
    display(result);
  } catch (error) {
    showErrorMessage(error.message);
  } finally {
    hideSpinner(); // always runs — success or failure
  }
}
</code></pre>
<p><code>hideSpinner()</code> runs whether <code>fetchSomething</code> succeeded or crashed. Without <code>finally</code>, you'd have to call <code>hideSpinner()</code> in both the <code>try</code> and the <code>catch</code>, duplicating cleanup logic. <code>finally</code> exists precisely for this: teardown, cleanup, resource release anything that must happen regardless of outcome.</p>
<p>Here's the full execution order laid out clearly:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/86b2e517-4fcb-49d2-b925-896d3f8b052f.png" alt="" style="display:block;margin:0 auto" />

<h2>Throwing custom errors</h2>
<p>JavaScript lets you throw anything but throwing a proper <code>Error</code> object (or a subclass of it) is best practice because it gives you a stack trace and a message.</p>
<pre><code class="language-javascript">function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

try {
  const result = divide(10, 0);
} catch (error) {
  console.error(error.message); // "Cannot divide by zero"
}
</code></pre>
<p>You're not waiting for JavaScript to fail you're proactively saying "this situation is invalid" and throwing your own error. The caller's <code>catch</code> block handles it just like any built-in error.</p>
<p>For larger applications, creating custom error classes makes your error handling more precise you can catch specific error types and respond differently:</p>
<pre><code class="language-javascript">class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

class NetworkError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = "NetworkError";
    this.statusCode = statusCode;
  }
}

function processForm(data) {
  if (!data.email.includes("@")) {
    throw new ValidationError("Invalid email address", "email");
  }
}

try {
  processForm({ email: "notanemail" });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(`Validation failed on field: ${error.field}`);
    highlightField(error.field);
  } else if (error instanceof NetworkError) {
    console.log(`Network failed with status: ${error.statusCode}`);
    showRetryButton();
  } else {
    console.error("Unexpected error:", error);
  }
}
</code></pre>
<p><code>instanceof</code> lets you branch on error type different failures get different responses instead of one generic "something went wrong" message.</p>
<h2>Error handling with async/await</h2>
<p><code>try/catch</code> works exactly the same way with <code>async/await</code>. Rejected promises become catchable errors:</p>
<pre><code class="language-javascript">async function loadUserData(id) {
  try {
    const response = await fetch(`/api/users/${id}`);

    if (!response.ok) {
      throw new NetworkError("Request failed", response.status);
    }

    const user = await response.json();
    return user;
  } catch (error) {
    if (error instanceof NetworkError) {
      console.error(`HTTP \({error.statusCode}: \){error.message}`);
    } else {
      console.error("Unexpected error:", error.message);
    }
    return null;
  } finally {
    hideLoadingIndicator();
  }
}
</code></pre>
<p>Same underlying problem. Completely different user experience. Error handling is how you translate a technical failure into a useful human message.</p>
<p>A pattern worth building into any serious application:</p>
<pre><code class="language-javascript">async function safeLoadDashboard() {
  try {
    const [user, stats, notifications] = await Promise.all([
      fetchUser(),
      fetchStats(),
      fetchNotifications()
    ]);

    renderDashboard(user, stats, notifications);
  } catch (error) {
    console.error("Dashboard load failed:", error);
    renderErrorState("Unable to load dashboard. Please refresh.");
  } finally {
    hideGlobalSpinner();
  }
}
</code></pre>
<p>If any of the three fetches fail, <code>catch</code> handles it.</p>
]]></content:encoded></item><item><title><![CDATA[Async/Await in JavaScript]]></title><description><![CDATA[You've met promises. You understand .then(). You've chained a few calls together and it mostly worked. But then you needed to do three async things in sequence, and you ended up with something like th]]></description><link>https://blogs.satpal.cloud/async-await-in-javascript</link><guid isPermaLink="true">https://blogs.satpal.cloud/async-await-in-javascript</guid><category><![CDATA[asynchronous]]></category><category><![CDATA[async/await]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 26 Mar 2026 16:53:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0ea37423-9879-4fab-9987-4a3a14a2f201.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've met promises. You understand <code>.then()</code>. You've chained a few calls together and it mostly worked. But then you needed to do three async things in sequence, and you ended up with something like this:</p>
<pre><code class="language-javascript">getUser(userId)
  .then(user =&gt; {
    return getOrders(user.id);
  })
  .then(orders =&gt; {
    return getProduct(orders[0].productId);
  })
  .then(product =&gt; {
    console.log(product.name);
  })
  .catch(err =&gt; {
    console.error(err);
  });
</code></pre>
<p>It works. But it reads sideways. Each <code>.then()</code> is a new indentation, a new callback, a new mental context to hold. You can't easily share variables between steps without hoisting them outside the chain. Error handling applies to the whole chain but it's tacked on at the end, invisible until something breaks.</p>
<p><code>async/await</code> was introduced in ES2017 to fix exactly this. Not by replacing promises by giving you a way to write promise-based code that looks and reads like regular synchronous code.</p>
<h2>Syntactic sugar over promises</h2>
<p>The first thing to understand is that <code>async/await</code> is not a new async system. It's a new <em>syntax</em> for working with promises. Under the hood, every <code>async</code> function returns a promise. Every <code>await</code> pauses execution and waits for a promise to resolve. No new engine magic just a cleaner way to write what you were already doing.</p>
<p>Think of it this way. Promises gave you a contract: "this will eventually have a value." <code>async/await</code> gives you a way to write code as if that value is already there, and JavaScript handles the waiting behind the scenes.</p>
<h2>The <code>async</code> keyword</h2>
<p>Putting <code>async</code> before a function declaration does one thing: it makes that function always return a promise. Even if you return a plain value, JavaScript automatically wraps it in a resolved promise.</p>
<pre><code class="language-javascript">async function greet() {
  return "Hello!";
}

greet().then(msg =&gt; console.log(msg)); // "Hello!"
</code></pre>
<p>You returned a string. But because the function is <code>async</code>, the caller receives a promise that resolves to that string. That's the contract.</p>
<p>You can use <code>async</code> with any function style:</p>
<pre><code class="language-javascript">// function declaration
async function fetchData() { ... }

// arrow function
const fetchData = async () =&gt; { ... }

// method in an object
const api = {
  async getUser() { ... }
};
</code></pre>
<h2>The <code>await</code> keyword</h2>
<p><code>await</code> can only live inside an <code>async</code> function. It pauses that function's execution until the promise it's waiting on resolves then hands you the resolved value directly.</p>
<pre><code class="language-javascript">async function loadUser() {
  const user = await getUser(1); // pauses here until resolved
  console.log(user.name);        // then continues
}
</code></pre>
<p>Without <code>await</code>, <code>getUser(1)</code> returns a promise object not the user. With <code>await</code>, you get the user directly, as if the function was synchronous. The pause is real but it's non-blocking: while this function is waiting, JavaScript keeps running everything else.</p>
<p>Here's what that promise chain from earlier looks like rewritten with <code>async/await</code>:</p>
<pre><code class="language-javascript">async function loadProductFromUser(userId) {
  const user    = await getUser(userId);
  const orders  = await getOrders(user.id);
  const product = await getProduct(orders[0].productId);

  console.log(product.name);
}
</code></pre>
<p>Top to bottom. Left to right. Each line waits for the previous one before moving on. No callbacks. No indentation staircase. It reads like a recipe: get the user, get their orders, get the first product, show its name.</p>
<p>Here's the execution flow when you call an <code>async</code> function:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0bfb2d33-c56f-4e7a-933b-12c20a99491b.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[JavaScript Promises Explained for Beginners]]></title><description><![CDATA[What problem do promises solve?
JavaScript is single-threaded. It runs one piece of code at a time, which means when you perform a slow operation, like fetching data from a server, reading a file, or ]]></description><link>https://blogs.satpal.cloud/javascript-promises-explained-for-beginners</link><guid isPermaLink="true">https://blogs.satpal.cloud/javascript-promises-explained-for-beginners</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[promises]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 26 Mar 2026 16:26:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f901a37b-c130-46de-9071-0ff0500e4c1d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What problem do promises solve?</h2>
<p>JavaScript is single-threaded. It runs one piece of code at a time, which means when you perform a slow operation, like fetching data from a server, reading a file, or waiting for a timer.</p>
<p>The entire thread can't afford to stop and wait. Instead, JavaScript uses an event-driven, asynchronous model: kick off the work, continue with other things, and handle the result when it's ready.</p>
<p>The earliest pattern for this was the <strong>callback</strong> you pass a function to another function, and that function calls yours back when the work completes. This works, but it breaks down fast. Imagine fetching a user, then fetching their posts, then fetching comments on each post. You end up nesting callbacks inside callbacks inside callbacks code that fans rightward across the screen, where error handling is duplicated at every level and the logical sequence of operations is buried in indentation. Developers called this callback hell.</p>
<p>Promises were introduced to solve this. A promise represents a value that isn't available <em>yet</em>, but will be in the future or won't arrive at all because something went wrong. Instead of passing callbacks into every function, you work with an object that carries the result of an asynchronous operation, with a clean, chainable API for handling success and failure.</p>
<h2>Promise states</h2>
<p>Every promise lives in exactly one of three states at any given moment:</p>
<p><strong>Pending</strong>: The operation is in progress. No result yet. This is the starting state.</p>
<p><strong>Fulfilled</strong>: The operation completed successfully. The promise now holds the resolved value.</p>
<p><strong>Rejected:</strong> The operation failed. The promise now holds a reason, typically an <code>Error</code> object explaining what went wrong.</p>
<p>The key rule: once a promise transitions out of pending, it never changes again. A fulfilled promise stays fulfilled forever. A rejected promise stays rejected. This predictability is one of the things that makes promises much easier to reason about than raw callbacks.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/fb72eabc-c603-4247-b60e-b84bb4d5917a.png" alt="" style="display:block;margin:0 auto" />

<h2>Creating a promise</h2>
<p>You create a promise by calling the <code>Promise</code> constructor and passing it an <strong>executor</strong>, a function that receives two callbacks: <code>resolve</code> and <code>reject</code>. You call one of them when the async work finishes.</p>
<pre><code class="language-javascript">const fetchUser = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; {
    const success = true; // pretend this comes from a network call

    if (success) {
      resolve({ id: 1, name: 'Priya' }); // fulfills the promise
    } else {
      reject(new Error('User not found')); // rejects the promise
    }
  }, 1000);
});
</code></pre>
<p>The executor runs immediately when <code>new Promise(...)</code> is called. The resolve and reject callbacks settle the promise and trigger any handlers that have been attached.</p>
<h2>Handling success and failure</h2>
<p>Once you have a promise, you react to its outcome using <code>.then()</code>, <code>.catch()</code>, and <code>.finally()</code>:</p>
<pre><code class="language-javascript">fetchUser
  .then((user) =&gt; {
    console.log('Got user:', user.name); // runs if resolved
  })
  .catch((error) =&gt; {
    console.error('Failed:', error.message); // runs if rejected
  })
  .finally(() =&gt; {
    console.log('Done loading'); // always runs
  });
</code></pre>
<p><code>.then()</code> receives the resolved value. <code>.catch()</code> receives the rejection reason. <code>.finally()</code> receives nothing.</p>
<p>It's purely for cleanup (hiding a loading spinner, closing a connection). A critical point: <code>.finally()</code> <strong>doesn't consume the promise value</strong>. Whatever the promise settled with flows through <code>.finally()</code> unchanged to any subsequent handler.</p>
<h2>Callbacks vs promises</h2>
<p>Let's look at a concrete comparison. Three sequential async operations: load a user, then load their orders, then calculate their total spend.</p>
<pre><code class="language-javascript">loadUser(userId, function(err, user) {
  if (err) return handleError(err);
  loadOrders(user.id, function(err, orders) {
    if (err) return handleError(err);
    calculateSpend(orders, function(err, total) {
      if (err) return handleError(err);
      console.log('Total spend:', total);
    });
  });
});
</code></pre>
<p><strong>With promises:</strong></p>
<pre><code class="language-javascript">loadUser(userId)
  .then((user) =&gt; loadOrders(user.id))
  .then((orders) =&gt; calculateSpend(orders))
  .then((total) =&gt; console.log('Total spend:', total))
  .catch(handleError);
</code></pre>
<p>The logic is identical. But the promise version reads like a linear sequence of steps because it is one. Error handling is consolidated in a single <code>.catch()</code> at the end rather than duplicated at every level.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/d8787c3c-4730-491f-8b8c-4a0bab9e1705.png" alt="" style="display:block;margin:0 auto" />

<h2>Promise chaining</h2>
<p>Promise chaining is possible because <code>.then()</code> always returns a new promise. Whatever value you <code>return</code> from inside a <code>.then()</code> callback becomes the resolved value of that new promise, which the next <code>.then()</code> in the chain receives.</p>
<pre><code class="language-javascript">fetchUser(1)
  .then((user) =&gt; {
    return fetchPostsByUser(user.id); // returns another promise
  })
  .then((posts) =&gt; {
    return posts.filter((p) =&gt; p.published); // returns a plain array
  })
  .then((publishedPosts) =&gt; {
    console.log(publishedPosts.length, 'published posts');
  })
  .catch((err) =&gt; {
    // any rejection in the chain above lands here
    console.error('Something went wrong:', err.message);
  });
</code></pre>
<p>The chain automatically unwraps promises: if you return a promise from inside <code>.then()</code>, the next <code>.then()</code> waits for that inner promise to settle before it fires. If you return a plain value, it's wrapped into a resolved promise automatically. This is the mechanism that makes chaining work seamlessly for both sync and async return values.</p>
<h2>A note on <code>async/await</code></h2>
<p>Modern JavaScript introduced <code>async/await</code> as syntax sugar built directly on top of promises. An <code>async</code> function always returns a promise, and <code>await</code> pauses execution inside that function until a promise settles without blocking the thread. It makes promise-based code look synchronous:</p>
<pre><code class="language-javascript">async function loadDashboard(userId) {
  try {
    const user = await fetchUser(userId);
    const orders = await fetchOrders(user.id);
    const total = await calculateSpend(orders);
    console.log('Total spend:', total);
  } catch (err) {
    console.error('Failed:', err.message);
  }
}
</code></pre>
<p>This is the same sequence as the promise chain above, just written differently. Understanding promises deeply states, <code>.then()</code>, <code>.catch()</code>, chaining is essential before <code>async/await</code> makes sense, because under the hood, that's exactly what it's doing.</p>
]]></content:encoded></item><item><title><![CDATA[String Polyfills in JavaScript]]></title><description><![CDATA[What are string methods?
In JavaScript, strings come with a powerful set of built-in methods functions attached to every string value that let you search, transform, slice, and inspect text. When you ]]></description><link>https://blogs.satpal.cloud/string-polyfills-in-javascript</link><guid isPermaLink="true">https://blogs.satpal.cloud/string-polyfills-in-javascript</guid><category><![CDATA[polyfills]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 26 Mar 2026 16:25:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/91df0725-22aa-4186-a7e8-a7e4c9442e65.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What are string methods?</h2>
<p>In JavaScript, strings come with a powerful set of built-in methods functions attached to every string value that let you search, transform, slice, and inspect text. When you call <code>"hello".toUpperCase()</code>, you're using a method that JavaScript's engine provides automatically. These aren't magic; they're functions defined on <code>String.prototype</code>, the shared blueprint that every string inherits from.</p>
<p>The key insight for interview preparation is this: knowing what a method does isn't enough. Interviewers want to know how it works and whether you could rebuild it from scratch. That's where polyfills come in.</p>
<h2>Why developers write polyfills</h2>
<p>A polyfill is a piece of code that implements a feature that the current runtime doesn't support or that you're implementing yourself to demonstrate understanding. When a new string method lands in the JavaScript specification, older browsers don't have it. Developers write polyfills to bridge that gap, attaching the implementation directly to <code>String.prototype</code> before the browser's built-in version would run.</p>
<p>But in interviews, polyfills serve a different purpose. They force you to reason about the logic behind familiar tools. Can you write <code>trim()</code> without calling <code>trim()</code>? Can you implement <code>includes()</code> using only index-based access? These questions reveal how deeply you understand strings as sequences of characters.</p>
<p>Here's how the string processing model works under the hood:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f69eaa1a-2166-4df1-8ff5-2e5970c4abfe.png" alt="" style="display:block;margin:0 auto" />

<p>One important detail the diagram highlights: strings in JavaScript are <strong>immutable</strong>. No string method ever modifies the original string.</p>
<h2>Implementing simple string utilities as polyfills</h2>
<p>Before writing a polyfill, always check if the method already exists. This prevents overwriting the native implementation in environments that support it.</p>
<pre><code class="language-javascript">if (!String.prototype.customTrim) {
  String.prototype.customTrim = function () {
    // `this` refers to the string value the method is called on
    let start = 0;
    let end = this.length - 1;

    while (start &lt;= end &amp;&amp; this[start] === ' ') start++;
    while (end &gt;= start &amp;&amp; this[end] === ' ') end--;

    return this.slice(start, end + 1);
  };
}
</code></pre>
<p>The logic here is a two-pointer approach.</p>
<p>Advance from the left until you hit a non-space character, retreat from the right until you hit a non-space character, then slice out the middle. This is exactly the kind of thinking interviews test: can you express a simple operation in terms of indices and comparisons?</p>
<p>Here's how the polyfill checking behavior works visually:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/c056b850-f3a8-4ce9-8183-0d3b01a966be.png" alt="" style="display:block;margin:0 auto" />

<h2>Common interview string methods to implement</h2>
<h3><code>includes(searchStr)</code></h3>
<p>The built-in method checks whether a substring exists anywhere in the string, returning <code>true</code> or <code>false</code>. The polyfill uses a sliding window: at every position, compare the next <code>searchStr.length</code> characters against the target.</p>
<pre><code class="language-javascript">String.prototype.myIncludes = function (searchStr) {
  const str = String(this);
  const search = String(searchStr);

  if (search.length === 0) return true;
  if (search.length &gt; str.length) return false;

  for (let i = 0; i &lt;= str.length - search.length; i++) {
    if (str.slice(i, i + search.length) === search) return true;
  }
  return false;
};
</code></pre>
<p>Note the edge cases: an empty search string always returns <code>true</code> (this matches the spec), and a search string longer than the source immediately returns <code>false</code>.</p>
<h3><code>repeat(count)</code></h3>
<p>This builds a new string by concatenating the original <code>count</code> times.</p>
<pre><code class="language-javascript">String.prototype.myRepeat = function (count) {
  const n = Math.floor(count);
  if (n &lt; 0 || n === Infinity) throw new RangeError('Invalid count value');
  let result = '';
  for (let i = 0; i &lt; n; i++) result += this;
  return result;
};
</code></pre>
<h3><code>startsWith(prefix)</code> and <code>endsWith(suffix)</code></h3>
<p>These are slice comparisons at fixed positions:</p>
<pre><code class="language-javascript">String.prototype.myStartsWith = function (prefix) {
  return this.slice(0, prefix.length) === prefix;
};

String.prototype.myEndsWith = function (suffix) {
  if (suffix.length === 0) return true;
  return this.slice(-suffix.length) === suffix;
};
</code></pre>
<h3><code>padStart(targetLength, padStr)</code> and <code>padEnd()</code></h3>
<p>Padding methods fill the string until it reaches a desired length:</p>
<pre><code class="language-javascript">String.prototype.myPadStart = function (targetLength, padStr = ' ') {
  const str = String(this);
  if (str.length &gt;= targetLength) return str;
  const padNeeded = targetLength - str.length;
  let padding = '';
  while (padding.length &lt; padNeeded) padding += padStr;
  return padding.slice(0, padNeeded) + str;
};
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Map and Set in JavaScript]]></title><description><![CDATA[What is a Map?
A Map is a collection of keyed data items, similar to an Object. However, the primary difference is that Map allows keys of any type functions, objects, or even primitives.
Map vs Objec]]></description><link>https://blogs.satpal.cloud/map-and-set-in-javascript</link><guid isPermaLink="true">https://blogs.satpal.cloud/map-and-set-in-javascript</guid><category><![CDATA[map]]></category><category><![CDATA[set]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 25 Mar 2026 17:02:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/a2e8c989-6b10-4705-98eb-d490571a0e82.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>What is a Map?</h2>
<p>A <strong>Map</strong> is a collection of keyed data items, similar to an Object. However, the primary difference is that Map allows keys of <strong>any type</strong> functions, objects, or even primitives.</p>
<h3>Map vs Object</h3>
<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>Object</strong></p></td><td><p><strong>Map</strong></p></td></tr><tr><td><p><strong>Key Types</strong></p></td><td><p>String or Symbol only</p></td><td><p>Any type (Objects, Funcs, etc.)</p></td></tr><tr><td><p><strong>Order</strong></p></td><td><p>Not reliably ordered</p></td><td><p>Maintains insertion order</p></td></tr><tr><td><p><strong>Size</strong></p></td><td><p>Manual calculation</p></td><td><p><code>.size</code> property</p></td></tr><tr><td><p><strong>Performance</strong></p></td><td><p>Better for small, static data</p></td><td><p>Better for frequent adds/removes</p></td></tr></tbody></table>

<h2>What is a Set?</h2>
<p>A <strong>Set</strong> is a collection of values where <strong>each value must be unique</strong>. Think of it as an Array with a built-in "no duplicates" policy.</p>
<h2>The Power of Uniqueness</h2>
<p>The most common use case for a Set is instantly cleaning an array. If you have a list of user IDs with duplicates, you can wipe them out in one line:</p>
<pre><code class="language-javascript">const uniqueIds = [...new Set([1, 2, 2, 3, 4, 4])]; // [1, 2, 3, 4]
</code></pre>
<h2>Set vs. Array</h2>
<ul>
<li><p><strong>Search Speed:</strong> Checking if an item exists in an Array (<code>arr.includes(x)</code>) takes O(n) time. In a Set (<code>set.has(x)</code>), it is O(1). If you have 10,000 items, the Set is orders of magnitude faster.</p>
</li>
<li><p><strong>No Duplicates:</strong> Arrays allow you to push the same value a million times. Sets silently ignore duplicates, keeping your data clean automatically.</p>
</li>
</ul>
<h2>When to reach for Map and Set</h2>
<h2>Use a Map when:</h2>
<ul>
<li><p>You need keys that aren't strings (e.g., associating metadata with a DOM element).</p>
</li>
<li><p>You need to frequently add and remove key-value pairs (Maps are optimized for this).</p>
</li>
<li><p>You need to iterate over data in the exact order it was added.</p>
</li>
</ul>
<h2>Use a Set when:</h2>
<ul>
<li><p>You are dealing with a list where duplicates are logically impossible or unwanted (like a list of "Liked" posts).</p>
</li>
<li><p>You need to perform high-speed "existence checks" (checking if a username is already taken in a local list).</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[Here's something that confuses almost every JavaScript beginner: there are two operators that look exactly the same both are just three dots ... but they do completely opposite things.
One expands thi]]></description><link>https://blogs.satpal.cloud/js-spread-vs-rest-operators</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-spread-vs-rest-operators</guid><category><![CDATA[spread vs rest javascript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 25 Mar 2026 16:49:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/00769750-ab7b-466e-8f38-0139b339bc6d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here's something that confuses almost every JavaScript beginner: there are two operators that look exactly the same both are just three dots <code>...</code> but they do completely opposite things.</p>
<p>One expands things out. The other collects things in.</p>
<p>By the end of this, you'll look at <code>...</code> and immediately know which one it is and what it's doing. Let's go.</p>
<h2>The Three Dots <code>...</code></h2>
<p>Before we split them apart, let's establish what they share.</p>
<p>Both the spread operator and the rest operator are written as <code>...</code> three dots, nothing more. JavaScript figures out which one you mean based entirely on where you use it.</p>
<p>Think of it like the word "run." The same word means completely different things in "I run every morning" and "a run of bad luck." Context does all the work. Same idea here.</p>
<h2>Spread</h2>
<p>Expanding Things Out. The spread operator takes something that's grouped together like an array or object and <strong>expands</strong> its contents out individually.</p>
<p>Imagine you have a box of apples. Spread tips the box over and lays every apple out on the table individually. The box is gone. Just apples.</p>
<pre><code class="language-js">const fruits = ["apple", "mango", "banana"];

console.log(fruits);    // ["apple", "mango", "banana"]  ← the box
console.log(...fruits); // apple mango banana             ← apples on table
</code></pre>
<p>That's it. <code>...fruits</code> says <em>don't give me the array, give me everything inside it.</em></p>
<h2>Rest</h2>
<p>Collecting Things In. The rest operator does the exact opposite. It takes a bunch of individual values and <strong>collects</strong> them into an array.</p>
<p>If spread tips the box over, rest is the box itself gathering loose items and packaging them together.</p>
<pre><code class="language-js">function collect(...items) {
  console.log(items); // ["apple", "mango", "banana"]
}

collect("apple", "mango", "banana");
</code></pre>
<p>You passed three separate strings. Rest collected them into one neat array called <code>items</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ecbaafa3-3493-4976-87bd-4f72fc7edf42.png" alt="" style="display:block;margin:0 auto" />

<h2>Spread with Arrays</h2>
<p>This is where spread gets genuinely useful. Here are the four things you'll do with it all the time.</p>
<p><strong>Copying an array:</strong></p>
<pre><code class="language-js">const original = [1, 2, 3];
const copy = [...original];

copy.push(4);

console.log(original); // [1, 2, 3] — untouched
console.log(copy);     // [1, 2, 3, 4]
</code></pre>
<p>Without spread, doing <code>const copy = original</code> just creates another pointer to the same array. Change one, change both. Spread makes a real independent copy.</p>
<p><strong>Merging arrays:</strong></p>
<pre><code class="language-js">const frontend = ["HTML", "CSS", "JavaScript"];
const backend  = ["Node.js", "Express", "MongoDB"];

const fullStack = [...frontend, ...backend];
// ["HTML", "CSS", "JavaScript", "Node.js", "Express", "MongoDB"]
</code></pre>
<p>Clean and readable. No loops. No <code>.concat()</code>.</p>
<p><strong>Adding items while spreading:</strong></p>
<pre><code class="language-js">const skills = ["CSS", "JavaScript"];
const updatedSkills = ["HTML", ...skills, "React"];
// ["HTML", "CSS", "JavaScript", "React"]
</code></pre>
<p>You can place <code>...</code> anywhere in the array literal. Items before, after, or both.</p>
<p><strong>Passing array items as function arguments:</strong></p>
<pre><code class="language-js">const nums = [4, 8, 2, 6];

console.log(Math.max(nums));    // NaN — Math.max wants numbers, not an array
console.log(Math.max(...nums)); // 8   — spread unpacks them perfectly
</code></pre>
<p><code>Math.max</code> expects individual numbers like <code>Math.max(4, 8, 2, 6)</code>. Spread converts your array into exactly that.</p>
<h2>Spread with Objects</h2>
<p>Spread works on objects too — and it's used constantly in modern JavaScript, especially in React.</p>
<p><strong>Copying an object:</strong></p>
<pre><code class="language-js">const user = { name: "Satpal", age: 25 };
const copy = { ...user };

copy.age = 30;

console.log(user.age); // 25 — original untouched
console.log(copy.age); // 30
</code></pre>
<p><strong>Merging objects:</strong></p>
<pre><code class="language-js">const defaults = { theme: "light", language: "en", fontSize: 14 };
const userPrefs = { theme: "dark", fontSize: 18 };

const settings = { ...defaults, ...userPrefs };
// { theme: "dark", language: "en", fontSize: 18 }
</code></pre>
<p>When keys clash, the last one wins. <code>userPrefs.theme</code> overwrote <code>defaults.theme</code>. This pattern — merge defaults, then override with user values is everywhere in real code.</p>
<p><strong>Updating one field without mutating:</strong></p>
<pre><code class="language-js">const user = { name: "Riya", age: 24, city: "Mumbai" };

const updated = { ...user, age: 25 };
// { name: "Riya", age: 25, city: "Mumbai" }
</code></pre>
<p>You spread all existing properties, then write the one you want to change. The original <code>user</code> object is never touched. This is the standard pattern in React state updates.</p>
<h2>Rest</h2>
<p>Collecting Function Arguments. Rest shines in functions. It lets you accept any number of arguments without knowing in advance how many there will be.</p>
<pre><code class="language-js">function sum(...numbers) {
  return numbers.reduce((total, n) =&gt; total + n, 0);
}

sum(1, 2);           // 3
sum(1, 2, 3, 4, 5);  // 15
sum(10, 20);         // 30
</code></pre>
<p><code>...numbers</code> scoops up every argument passed in and packages them into an array. Then you can use all your normal array methods on them.</p>
<p><strong>Mix regular parameters with rest:</strong></p>
<pre><code class="language-js">function introduce(greeting, ...names) {
  names.forEach(name =&gt; {
    console.log(greeting + ", " + name + "!");
  });
}

introduce("Hello", "Priya", "Arjun", "Dev");
// Hello, Priya!
// Hello, Arjun!
// Hello, Dev!
</code></pre>
<p><code>greeting</code> catches the first argument normally. <code>...names</code> catches everything after it. The rest parameter must always come last nothing can follow it.</p>
<p>Difference:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/9f33484f-698f-4f7b-a57f-ecef821ecfaf.png" alt="" style="display:block;margin:0 auto" />

<p>What it does:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/b8697301-68dd-43ac-92ef-66a1d967a44d.png" alt="" style="display:block;margin:0 auto" />

<p>Quick Rule:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/9d73a332-ae1c-4518-b953-dcdf8b62fe22.png" alt="" style="display:block;margin:0 auto" />

<h2>The Quick Reference</h2>
<table>
<thead>
<tr>
<th></th>
<th>Spread</th>
<th>Rest</th>
</tr>
</thead>
<tbody><tr>
<td>Symbol</td>
<td><code>...</code></td>
<td><code>...</code></td>
</tr>
<tr>
<td>Direction</td>
<td>Expands out</td>
<td>Collects in</td>
</tr>
<tr>
<td>Used in</td>
<td>Array literals, object literals, function calls</td>
<td>Function parameter lists</td>
</tr>
<tr>
<td>Input</td>
<td>Array / object / iterable</td>
<td>Individual arguments</td>
</tr>
<tr>
<td>Output</td>
<td>Individual values</td>
<td>An array</td>
</tr>
<tr>
<td>Must be last?</td>
<td>No</td>
<td>Yes, always last parameter</td>
</tr>
<tr>
<td>Works with objects?</td>
<td>Yes</td>
<td>No, only in destructuring</td>
</tr>
</tbody></table>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[Picture this. You get back a user object from an API. It has a name, an email, an age, a city, a subscription plan. You need to use four of those five values across the next twenty lines of code.
So y]]></description><link>https://blogs.satpal.cloud/js-destructuring</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-destructuring</guid><category><![CDATA[Destructuring]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 25 Mar 2026 16:38:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/def9eb10-5b07-419e-a11b-8c2ebcd0ce6a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture this. You get back a user object from an API. It has a name, an email, an age, a city, a subscription plan. You need to use four of those five values across the next twenty lines of code.</p>
<p>So you write this:</p>
<pre><code class="language-javascript">const user = {
  name: "Priya",
  email: "priya@example.com",
  age: 28,
  city: "Pune",
  plan: "premium"
};

console.log(user.name);
console.log(user.email);
console.log(user.age);
console.log(user.city);
</code></pre>
<p>It works. But <code>user.</code> appears everywhere.</p>
<p>Destructuring is JavaScript's way of saying: pull out what you need, give it a name, and work with it directly.</p>
<h2>What destructuring means</h2>
<p>Destructuring is a syntax for unpacking values from arrays or properties from objects into individual variables. In one line, you extract multiple values and name them. After that line, you work with plain variables no more reaching back into the original structure every time.</p>
<p>It doesn't modify the original object or array. It just creates new variables that hold copies of the values.</p>
<h2>Destructuring objects</h2>
<p>The syntax uses curly braces on the left side of an assignment. The variable names inside the braces must match the property names in the object.</p>
<pre><code class="language-javascript">const user = {
  name: "Priya",
  email: "priya@example.com",
  age: 28,
  city: "Pune"
};

const { name, email, age } = user;

console.log(name);  // "Priya"
console.log(email); // "priya@example.com"
console.log(age);   // 28
</code></pre>
<p>One line. Three variables. You've extracted exactly what you need and nothing more. After that line, you just use <code>name</code>, <code>email</code>, <code>age</code> clean, direct, no repeated <code>user.</code> prefix.</p>
<p>Here's what's actually happening each variable on the left matches a key in the object, and gets assigned that key's value:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/9c0aeffa-61ac-40be-b7b3-6be75c323edf.png" alt="" style="display:block;margin:0 auto" />

<h3>Renaming while destructuring</h3>
<p>What if a property name is too generic, or clashes with another variable in your scope? You can rename on the fly using a colon:</p>
<pre><code class="language-javascript">const { name: userName, city: userCity } = user;

console.log(userName); // "Priya"
console.log(userCity); // "Pune"
</code></pre>
<p>Read the colon as "rename to". The left side is the key to look for in the object. The right side is the variable name you want locally.</p>
<h2>Destructuring arrays</h2>
<p>Array destructuring uses square brackets instead of curly braces. Here, order matters variables are assigned based on their position in the array, not by name.</p>
<pre><code class="language-javascript">const scores = [95, 82, 77, 68, 55];

const [first, second, third] = scores;

console.log(first);  // 95
console.log(second); // 82
console.log(third);  // 77
</code></pre>
<p>The first variable gets index 0, the second gets index 1, and so on. The rest of the array is simply ignored.</p>
<p>Need to skip a position? Leave a hole with a comma:</p>
<pre><code class="language-javascript">const [top, , bronze] = scores;

console.log(top);    // 95
console.log(bronze); // 77
</code></pre>
<p>The empty slot between the two commas skips index 1 entirely. You're essentially saying: "I want position 0 and position 2, nothing else."</p>
<p>Here's the positional mapping laid out:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/5cc5b54e-389b-46f4-9b05-c68c951c5e88.png" alt="" style="display:block;margin:0 auto" />

<h3>The swap trick</h3>
<p>One of the most satisfying uses of array destructuring is swapping two variables without a temporary holder:</p>
<pre><code class="language-javascript">let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a); // 20
console.log(b); // 10
</code></pre>
<p>Before destructuring, swapping required three lines and a <code>temp</code> variable. Now it's one line and reads almost like plain English.</p>
<h2>Default values</h2>
<p>What happens when you destructure a property that doesn't exist? You get <code>undefined</code>. Default values let you specify a fallback instead.</p>
<p><strong>In object destructuring:</strong></p>
<pre><code class="language-javascript">const settings = { theme: "dark" };

const { theme, fontSize = 16, language = "en" } = settings;

console.log(theme);    // "dark"    — came from the object
console.log(fontSize); // 16        — default, not in object
console.log(language); // "en"      — default, not in object
</code></pre>
<p>The default only kicks in when the value is <code>undefined</code>. If the property exists but is set to <code>null</code> or <code>0</code> or <code>""</code>, the default is ignored — those are real values.</p>
<h3>In array destructuring:</h3>
<pre><code class="language-javascript">const colors = ["red"];

const [primary = "blue", secondary = "gray"] = colors;

console.log(primary);   // "red"  — came from array
console.log(secondary); // "gray" — default, array only had one item
</code></pre>
<p>This is especially useful when writing functions that accept optional configuration you give sensible defaults right at the destructuring line instead of writing a wall of <code>if</code> checks inside the function body.</p>
<h2>Destructuring in function parameters</h2>
<p>This is where destructuring really starts to clean up real code. Instead of receiving an object and then reaching into it, you destructure it directly in the parameter list:</p>
<pre><code class="language-javascript">function renderProfile(user) {
  return `\({user.name}, \){user.age} — ${user.city}`;
}

function renderProfile({ name, age, city }) {
  return `\({name}, \){age} — ${city}`;
}

renderProfile({ name: "Rohan", age: 24, city: "Delhi" });
</code></pre>
<p>The second version is self-documenting. Anyone reading the function signature immediately knows what properties it expects. You don't have to read the function body to understand what shape the argument needs to have.</p>
<p>Add defaults to parameter destructuring and you get optional configurations for free:</p>
<pre><code class="language-javascript">function createButton({ label, color = "blue", size = "md", disabled = false }) {
  return `&lt;button class="\({color} \){size}" \({disabled ? "disabled" : ""}&gt;\){label}&lt;/button&gt;`;
}

createButton({ label: "Submit" });


createButton({ label: "Delete", color: "red", disabled: true });
</code></pre>
<p>Destructuring is JavaScript telling you: <em>stop reaching into the same container over and over. Take what you need, name it, and work with it.</em></p>
<p>Arrays give you positional unpacking. Objects give you name-based unpacking. Both support default values, renaming, and nesting. And when you combine destructuring with function parameters, your code stops describing <em>how</em> it gets its data and starts describing <em>what</em> it does with it.</p>
<p>Every time you find yourself writing <a href="http://something.property"><code>something.property</code></a> three times in a row that's your cue to destructure.</p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[You've been there. You're building something, and you need to put a name inside a sentence. So you write this:
const name = "Priya";
const age = 28;

const message = "Hello, my name is " + name + " an]]></description><link>https://blogs.satpal.cloud/js-template-literals</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-template-literals</guid><category><![CDATA[template literals]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 25 Mar 2026 16:26:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/115f1ddf-1744-4b2f-8ff1-91ef7dfcee1c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've been there. You're building something, and you need to put a name inside a sentence. So you write this:</p>
<pre><code class="language-javascript">const name = "Priya";
const age = 28;

const message = "Hello, my name is " + name + " and I am " + age + " years old.";
</code></pre>
<p>It works. You move on. Then the string gets longer. You add another variable. Then a condition. Then a line break. And suddenly you're staring at something that looks like this:</p>
<pre><code class="language-javascript">const html = "&lt;div class='card'&gt;" +
  "&lt;h2&gt;" + user.name + "&lt;/h2&gt;" +
  "&lt;p&gt;Age: " + user.age + "&lt;/p&gt;" +
  "&lt;p&gt;Role: " + user.role + "&lt;/p&gt;" +
"&lt;/div&gt;";
</code></pre>
<p>Count the quotes. Count the plus signs. Miss one closing quote and the whole thing breaks —and the error message won't even tell you where.</p>
<p>This is the problem template literals solve. Not just cosmetically. They fundamentally change how you think about building strings in JavaScript.</p>
<h2>What template literals actually are</h2>
<p>A template literal is a string wrapped in backticks instead of single or double quotes.</p>
<pre><code class="language-javascript">const simple = `Hello, world`;
</code></pre>
<p>That's it at the surface level. But backticks unlock three things that regular quotes simply can't do: embedding expressions directly into strings, writing multi-line strings without any tricks, and running logic inside a string all without a single <code>+</code> operator.</p>
<h2>Backticks and <code>${}</code></h2>
<p>The full syntax has two parts. The backtick wraps the whole string. The <code>\({}</code> is the slot where you embed anything a variable, a calculation, a function call, a ternary. Whatever JavaScript expression you put inside <code>\){}</code> gets evaluated and inserted into the string at that position.</p>
<pre><code class="language-javascript">const name = "Ankit";
const age = 22;

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

console.log(message);
// Hello, my name is Ankit and I am 22 years old.
</code></pre>
<p>No plus signs. No closing and reopening quotes. The string reads like a sentence because it <em>is</em> a sentence, with slots in it.</p>
<h2>Old way vs new way: a direct comparison</h2>
<p>Let's put them side by side so the difference is impossible to miss.</p>
<p><strong>Old way:</strong></p>
<pre><code class="language-javascript">const user = { name: "Rohan", city: "Mumbai" };

const greeting = "Welcome back, " + user.name + "! We see you're logging in from " + user.city + ".";
</code></pre>
<p><strong>Template literal:</strong></p>
<pre><code class="language-javascript">const greeting = `Welcome back, \({user.name}! We see you're logging in from \){user.city}.`;
</code></pre>
<p>Same output. But the second version reads like English. You don't have to mentally parse where the string ends and the variable begins they're woven together.</p>
<h2>Embedding expressions, not just variables</h2>
<p><strong>Math directly in the string:</strong></p>
<pre><code class="language-javascript">const price = 120;
const qty = 3;
const tax = 0.18;

const bill = `Subtotal: ₹\({price * qty}. With tax: ₹\){(price * qty * (1 + tax)).toFixed(2)}`;

console.log(bill);
// Subtotal: ₹360. With tax: ₹424.80
</code></pre>
<p><strong>A ternary for conditional text:</strong></p>
<pre><code class="language-javascript">const user = { name: "Sneha", isPremium: true };

const badge = `\({user.name} — \){user.isPremium ? "Premium member" : "Free tier"}`;

console.log(badge);
// Sneha — Premium member
</code></pre>
<p><strong>A function call:</strong></p>
<pre><code class="language-javascript">const formatDate = (d) =&gt; d.toLocaleDateString("en-IN");

const message = `Report generated on ${formatDate(new Date())}`;

console.log(message);
// Report generated on 25/03/2026
</code></pre>
<p>The string becomes a living thing. Instead of building the value outside and plugging it in as a variable, you can do the work right inside the string. For simple cases this is enormously readable.</p>
<h2>Multi-line strings: no more <code>\n</code></h2>
<p>Before template literals, writing a multi-line string looked like one of two painful options:</p>
<pre><code class="language-javascript">// Option 1 — \n escape sequences
const poem = "Roses are red,\nViolets are blue,\nJavaScript is fun,\nAnd so are you.";

// Option 2 — concatenation across lines
const poem = "Roses are red,\n" +
             "Violets are blue,\n" +
             "JavaScript is fun,\n" +
             "And so are you.";
</code></pre>
<p>Both work. Neither looks like a poem. With template literals, you just press Enter:</p>
<pre><code class="language-javascript">const poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;

console.log(poem);
// Roses are red,
// Violets are blue,
// JavaScript is fun,
// And so are you.
</code></pre>
<p>The line breaks in your source code become line breaks in the string. What you see is what you get.</p>
]]></content:encoded></item><item><title><![CDATA[The new Keyword in JavaScript: ]]></title><description><![CDATA[You've probably written something like this without thinking twice:
javascript
const today = new Date();
const pattern = new RegExp("hello");

That new sitting there what is it actually doing?
Most tu]]></description><link>https://blogs.satpal.cloud/js-new</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-new</guid><category><![CDATA[new keyword]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Tue, 24 Mar 2026 17:39:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/c35bb023-d5c0-4b51-988c-61db5ff34955.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've probably written something like this without thinking twice:</p>
<p>javascript</p>
<pre><code class="language-javascript">const today = new Date();
const pattern = new RegExp("hello");
</code></pre>
<p>That <code>new</code> sitting there what is it actually doing?</p>
<p>Most tutorials hand-wave it as it creates an object. And technically that's true. But there's a four-step process happening every time you type <code>new</code>, and once you see it laid out clearly, a lot of things in JavaScript prototypes, instances, <code>this</code>, class syntax suddenly snap into place.</p>
<p>Let's build this understanding from the ground up.</p>
<pre><code class="language-javascript">const today = new Date();
const pattern = new RegExp("hello");
</code></pre>
<p>That <code>new</code> sitting there — what is it actually doing? Most tutorials hand-wave it as "it creates an object." And technically that's true. But there's a four-step process happening every time you type <code>new</code>, and once you see it laid out clearly, a lot of things in JavaScript — prototypes, instances, <code>this</code>, class syntax — suddenly snap into place.</p>
<p>Let's build this understanding from the ground up.</p>
<h2>The problem <code>new</code> is solving</h2>
<p>Before <code>new</code> makes sense, the problem it solves needs to make sense.</p>
<p>Say you're building a simple app and you need to represent multiple users. The naive approach is just making plain objects:</p>
<pre><code class="language-javascript">const user1 = { name: "Ankit", age: 22, role: "admin" };
const user2 = { name: "Priya", age: 28, role: "editor" };
const user3 = { name: "Rohan", age: 19, role: "viewer" };
</code></pre>
<p>This works. For three users. But what happens when you have 300? You're copying the same shape by hand every time, with no guarantee the structure stays consistent. Miss a property on user 147 and you've got a bug that's annoying to track down.</p>
<p>What you really want is a template something you call once and get back a properly-shaped object every time. That's exactly what a constructor function is.</p>
<h2>Constructor functions: a template for objects</h2>
<p>A constructor function is just a regular function that you intend to call with <code>new</code>. By convention, its name starts with a capital letter not a rule JavaScript enforces, but a strong signal to anyone reading your code.</p>
<pre><code class="language-javascript">function User(name, age, role) {
  this.name = name;
  this.age = age;
  this.role = role;
}
</code></pre>
<p>That <code>this</code> inside the function is the key. When you call it with <code>new</code>, <code>this</code> refers to the brand new object being created. Every property you attach to <code>this</code> ends up on that new object.</p>
<p>Now you can create as many users as you need:</p>
<pre><code class="language-javascript">const user1 = new User("Ankit", 22, "admin");
const user2 = new User("Priya", 28, "editor");
const user3 = new User("Rohan", 19, "viewer");

console.log(user1.name); // "Ankit"
console.log(user2.role); // "editor"
</code></pre>
<p>Each call to <code>new User(...)</code> produces a fresh, independent object. Change <a href="http://user1.name"><code>user1.name</code></a> and <a href="http://user2.name"><code>user2.name</code></a> doesn't budge. They share a shape but not their data.</p>
<h2>The four things <code>new</code> does</h2>
<p>This is the part most explanations skip. When you write <code>new User("Ankit", 22, "admin")</code>, JavaScript silently does four things in sequence. Understanding these four steps is the unlock for everything else.</p>
<h3><strong>Step 1</strong></h3>
<p><strong>A blank object is created.</strong> JavaScript creates a fresh <code>{}</code>. Nothing on it yet. This is the object that will eventually be returned.</p>
<h3><strong>Step 2</strong></h3>
<p><strong>The prototype is linked.</strong> That blank object gets its internal <code>[[Prototype]]</code> set to <code>User.prototype</code>. This is how the object inherits methods. More on this in a moment.</p>
<h3><strong>Step 3</strong></h3>
<p><strong>The constructor runs with</strong> <code>this</code> <strong>pointing to the new object.</strong> <code>User</code> is called, and inside it, every <code>this.something = ...</code> line adds properties to that blank object. This is where your data lands.</p>
<p><strong>Step 4</strong></p>
<p><strong>The new object is returned.</strong> If your constructor function doesn't explicitly return an object, JavaScript returns <code>this</code> automatically the fully populated object from step 3.</p>
<p>Here's how all four steps look if you imagine JavaScript doing it manually:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/46d1dde7-3453-476e-be32-4c7baad74949.png" alt="" style="display:block;margin:0 auto" />

<h2>Prototype linking</h2>
<p>Step 2 is the one that confuses people most, so let's give it the attention it deserves.</p>
<p>Every function in JavaScript automatically gets a <code>prototype</code> property it's an object that sits attached to the function. When you create an instance with <code>new</code>, that instance gets a hidden link back to the constructor's <code>prototype</code>. This link is what JavaScript follows when it can't find a property directly on the object.</p>
<p>Here's why this matters in practice. Instead of defining <code>greet</code> directly on every instance (which would create a new copy of the function for each object), you put it on the prototype once:</p>
<pre><code class="language-javascript">function User(name, age) {
  this.name = name;
  this.age = age;
}

User.prototype.greet = function() {
  console.log("Hi, I'm " + this.name);
};

const user1 = new User("Ankit", 22);
const user2 = new User("Priya", 28);

user1.greet(); // "Hi, I'm Ankit"
user2.greet(); // "Hi, I'm Priya"
</code></pre>
<p><code>user1</code> and <code>user2</code> don't have <code>greet</code> on them directly. But when JavaScript looks for <code>greet</code> on <code>user1</code>, it follows the hidden prototype link up to <code>User.prototype</code> and finds it there. One function, shared by every instance.</p>
<p>Here's the relationship laid out visually:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0c756431-c729-4474-8ad0-36d3d3c4add8.png" alt="" style="display:block;margin:0 auto" />

<p>The instances own their own data. The shared behavior lives on the prototype above them. That's the whole model.</p>
<h2>Instances</h2>
<p>Every object created with <code>new SomeFunction()</code> is called an <em>instance</em> of that constructor. JavaScript gives you a way to verify this:</p>
<pre><code class="language-javascript">console.log(user1 instanceof User); // true
console.log(user2 instanceof User); // true
</code></pre>
<p><code>instanceof</code> checks whether <code>User.prototype</code> is anywhere in the object's prototype chain. Since we linked it in step 2, the answer is always <code>true</code> for objects created with <code>new User</code>.</p>
<p>You can also check which constructor built an object:</p>
<pre><code class="language-javascript">console.log(user1.constructor === User); // true
</code></pre>
<p>This is useful when you're debugging and want to confirm an object came from the constructor you think it did.</p>
<h2>What happens if you forget <code>new</code></h2>
<p>This is a classic beginner mistake and it fails in a confusing way:</p>
<pre><code class="language-javascript">const user = User("Ankit", 22, "admin"); // no new!

console.log(user);       // undefined
console.log(window.name); // "Ankit" — oops
</code></pre>
<p>Without <code>new</code>, the function runs as a regular function. There's no blank object created, nothing gets returned. Worse, <code>this</code> inside the function points to the global object so <a href="http://this.name"><code>this.name</code></a> <code>= "Ankit"</code> pollutes the global scope. This is exactly the kind of bug that takes twenty minutes to find.</p>
<p>The capital-letter naming convention exists precisely to signal: call this with <code>new</code>, not without it.</p>
<h2>Classes</h2>
<p>If you've used ES6 classes, here's something worth knowing: they are not a new object system. They're syntactic sugar over exactly what we just covered.</p>
<pre><code class="language-javascript">class User {
  constructor(name, age, role) {
    this.name = name;
    this.age = age;
    this.role = role;
  }

  greet() {
    console.log("Hi, I'm " + this.name);
  }
}

const user1 = new User("Ankit", 22, "admin");
</code></pre>
<p>Under the hood, this is identical to the constructor function + prototype version we wrote earlier. The <code>constructor</code> method is the function body. The <code>greet</code> method goes on <code>User.prototype</code> automatically. JavaScript is still running the same four-step process when you call <code>new User(...)</code>.</p>
<p>The <code>class</code> syntax is cleaner to read and write especially when inheritance gets involved but it's not doing anything fundamentally different. Once you understand what <code>new</code> actually does, class syntax stops being magic and starts being shorthand.\</p>
]]></content:encoded></item><item><title><![CDATA[Callback Functions in JavaScript]]></title><description><![CDATA[You've probably typed something like this and moved on without really thinking about it:
setTimeout(function() {
  console.log("hello");
}, 1000);

That function you passed inside setTimeout?
That's a]]></description><link>https://blogs.satpal.cloud/js-callback</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-callback</guid><category><![CDATA[callback]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Tue, 24 Mar 2026 17:18:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/4d455d27-63d5-4ed9-b246-a69501ec3f34.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've probably typed something like this and moved on without really thinking about it:</p>
<pre><code class="language-javascript">setTimeout(function() {
  console.log("hello");
}, 1000);
</code></pre>
<p>That function you passed inside <code>setTimeout</code>?</p>
<p>That's a callback. And once you truly understand what's happening there, a huge chunk of JavaScript events, fetch, promises, array methods, suddenly makes complete sense.</p>
<p>Let's start from the very beginning.</p>
<h2>Functions Are Just Values</h2>
<p>Before we even touch callbacks, you need to see something that surprises a lot of beginners.</p>
<p>In JavaScript, a function isn't special. It's just a value like a number, a string, or an object. That means you can store it in a variable, put it in an array, and yes, pass it as an argument to another function.</p>
<p>Watch:</p>
<pre><code class="language-javascript">// a number stored in a variable
const age = 25;

// a string stored in a variable
const name = "Satpal";

// a function stored in a variable — same idea
const greet = function() {
  console.log("Hello!");
};
</code></pre>
<p><code>greet</code> is just a variable that holds a function. You can pass it around exactly like you'd pass <code>age</code> or <code>name</code>. This one idea is the entire foundation of callbacks.</p>
<h2>So What Is a Callback Function?</h2>
<p>A callback is simply a function that you pass <em>into</em> another function, so that other function can call it later.</p>
<p>That's it. Nothing magical. Just a function being passed as an argument.</p>
<pre><code class="language-javascript">function doSomething(callback) { 
    console.log("doing the task...");    
    callback(); // calling the function you passed in 
}

function finished() {
  console.log("task complete!");
}


doSomething(finished);

// Output:
// doing the task...
// task complete!
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/4c488a9a-685b-4c90-8be5-0dd34ccbf913.png" alt="" style="display:block;margin:0 auto" />

<p>Notice: we wrote <code>finished</code> not <code>finished()</code>. When you write <code>finished()</code>, you're calling it right then. When you write <code>finished</code>, you're passing the function itself handing it over like a recipe card. The other function decides when to cook.</p>
<h2>A Real-World Analogy</h2>
<p>Think about ordering food at a restaurant.</p>
<p>You place your order and give the waiter your phone number. You don't stand at the counter waiting. You go sit down. When the food is ready, the kitchen <em>calls you back</em>.</p>
<p>Your phone number is the callback. You handed it over and said "call this when the thing is done."</p>
<p>JavaScript works exactly the same way. You hand a function over and say "run this when you're done."</p>
<h2>Passing Functions as Arguments</h2>
<p>Let's see this in non-async situations first, because callbacks are not just an async thing.</p>
<p><strong>Example 1:</strong></p>
<p><strong>A simple custom function:</strong></p>
<pre><code class="language-javascript">function greetUser(name, callback) {
  const message = "Hello, " + name + "!";
  callback(message); // passes the message to your callback
}

greetUser("Priya", function(msg) {
  console.log(msg); // Hello, Priya!
});
</code></pre>
<p><strong>Example 2 — you already use callbacks with array methods:</strong></p>
<pre><code class="language-javascript">const numbers = [1, 2, 3, 4, 5];

// the function you pass to .filter() is a callback
const evens = numbers.filter(function(num) {
  return num % 2 === 0;
});

console.log(evens); // [2, 4]
</code></pre>
<p>Every time you use <code>.map()</code>, <code>.filter()</code>, <code>.forEach()</code>, <code>.sort()</code> — you are already writing callbacks. Every day. You just might not have called them that.</p>
<h2>Why callbacks exist</h2>
<p>Here's the real reason callbacks are everywhere. JavaScript runs in a single thread. That means it can only do one thing at a time. When it hits something slow — a network request, a file read, a timer it can't just freeze and wait. The whole page would lock up.</p>
<p>So instead, JavaScript says: <em>"I'll start this task, then come back to the rest of the code. When the slow thing finishes, call this function."</em></p>
<pre><code class="language-javascript">console.log("1. Start");

setTimeout(function() {
  console.log("2. This runs after 2 seconds");
}, 2000);

console.log("3. This runs immediately");

// Output:
// 1. Start
// 3. This runs immediately
// 2. This runs after 2 seconds   ← came back later
</code></pre>
<p>JavaScript didn't pause at the <code>setTimeout</code>. It registered your callback, moved on, and came back when the timer expired. That's the whole idea.</p>
<h2>Callbacks in common scenarios</h2>
<p>You see this pattern everywhere once you know what to look for.</p>
<p><strong>Reading a file (Node.js):</strong></p>
<pre><code class="language-javascript">fs.readFile("data.txt", function(error, content) {
  if (error) {
    console.log("Something went wrong");
    return;
  }
  console.log(content);
});
</code></pre>
<p><strong>Listening for a button click:</strong></p>
<pre><code class="language-javascript">button.addEventListener("click", function() {
  console.log("button was clicked!");
});
</code></pre>
<p><strong>Fetching data from an API (older style):</strong></p>
<pre><code class="language-javascript">fetchUserData(userId, function(user) {
  console.log("Got user:", user.name);
});
</code></pre>
<p>In every case, the pattern is the same. You're handing off a function and saying: <em>run this when you have the result.</em></p>
<h2>Callback nesting</h2>
<p>Now for the part nobody warns you about early enough.</p>
<p>Callbacks work great for one operation. But real applications chain operations. Get the user, then get their orders, then get each product in the order. Each step needs the result from the previous one. So you nest a callback inside a callback inside a callback.</p>
<pre><code class="language-javascript">getUser(userId, function(user) {
  getOrders(user.id, function(orders) {
    getProduct(orders[0].productId, function(product) {
      getReviews(product.id, function(reviews) {
        console.log(reviews); // finally got what we needed
      });
    });
  });
});
</code></pre>
<p>Every new requirement pushes the code one level deeper. This is what developers call <strong>callback hell</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/34f5777d-c5c9-4e6f-a6a0-314b32a614cf.png" alt="" style="display:block;margin:0 auto" />

<p>The problem isn't just visual. Code this deep is genuinely hard to maintain. Add error handling at each level and it gets worse. Move a step around and you're hunting through nested brackets. Debug it and you're tracing a path through a maze.</p>
<p>This is not a hypothetical problem it's what pushed the JavaScript community to invent <strong>Promises</strong> and then <strong>async/await</strong>. Those tools exist entirely to solve the mess callbacks create when chained.</p>
<p>But here's the important thing to remember: Promises and async/await don't eliminate callbacks. They're built on top of the same concept. Understanding callbacks <em>is</em> understanding the foundation of async JavaScript.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the this Keyword in JavaScript]]></title><description><![CDATA[If there's one thing that confuses JavaScript developers more than anything else, for beginner and experienced both it's this.
It looks simple. But it behaves differently depending on where you use it]]></description><link>https://blogs.satpal.cloud/js-this-detail</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-this-detail</guid><category><![CDATA[this keyword]]></category><category><![CDATA[this]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Tue, 24 Mar 2026 17:04:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/80c966ff-bd13-448c-9cfa-8be3df8baea4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If there's one thing that confuses JavaScript developers more than anything else, for beginner and experienced both it's <code>this</code>.</p>
<p>It looks simple. But it behaves differently depending on where you use it, how you call a function, and sometimes even whether you're in strict mode or not.</p>
<p>By the end of this, you'll stop guessing what <code>this</code> is. You'll know.</p>
<h2>Thumb Rule</h2>
<p>Before any examples, here's the single most important thing to understand about <code>this</code>:</p>
<blockquote>
<p><code>this</code> <strong>is not about where a function is defined. It's about who calls it.</strong></p>
</blockquote>
<p>Read that again. Burn it in.</p>
<p>Most <code>this</code> confusion comes from thinking that <code>this</code> is locked to the function at the time you write it. It isn't. <code>this</code> is decided at the moment the function is called based on what's to the left of the dot.</p>
<p>That's the whole secret. Everything else is just variations of that rule.</p>
<h2>Visualizing Caller to Function Relationship</h2>
<p>Think of every function call as a conversation. Someone calls the function. That someone is <code>this</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/676a3c5b-6787-43be-906e-65ce77ca67e8.png" alt="" style="display:block;margin:0 auto" />

<p>Same function. Different caller. Different <code>this</code>. That's the whole game.</p>
<h2><code>this</code> in the Global Context</h2>
<p>When you open a JavaScript file and write <code>this</code> outside of any function or object, it refers to the <strong>global object</strong>.</p>
<p>In a browser, that's <code>window</code>. In Node.js, that's <code>global</code>.</p>
<pre><code class="language-javascript">console.log(this); // window (in browser)

function showThis() {
  console.log(this); // also window — no caller, so global is assumed
}

showThis();
</code></pre>
<p>Think of the global object as the default owner of everything. When there's no specific caller, the global context steps in.</p>
<p><strong>In strict mode, this changes:</strong></p>
<pre><code class="language-javascript">"use strict";

function showThis() {
  console.log(this); // undefined — strict mode removes the global fallback
}

showThis();
</code></pre>
<p>This is a common gotcha. Strict mode is more honest it says there's no caller here, so <code>this</code> is nothing instead of quietly pointing to <code>window</code>.</p>
<h2><code>this</code> Inside Objects</h2>
<p>This is where <code>this</code> starts feeling genuinely useful.</p>
<p>When a function lives inside an object and you call it <em>through</em> that object, <code>this</code> refers to the object itself.</p>
<pre><code class="language-javascript">const user = {
  name: "Satpal",
  greet: function() {
    console.log("Hello, " + this.name);
  }
};

user.greet(); // Hello, Satpal
</code></pre>
<p><code>user</code> is to the left of the dot. So <code>this</code> inside <code>greet</code> is <code>user</code>. JavaScript looks left of the dot — that's what <code>this</code> gets set to.</p>
<p><strong>Multiple methods sharing</strong> <code>this</code><strong>:</strong></p>
<pre><code class="language-javascript">const counter = {
  count: 0,
  increment: function() {
    this.count++;
  },
  reset: function() {
    this.count = 0;
  },
  show: function() {
    console.log("Count:", this.count);
  }
};

counter.increment();
counter.increment();
counter.show();  // Count: 2
counter.reset();
counter.show();  // Count: 0
</code></pre>
<p>Every method can talk to the same object's data through <code>this</code>. That's exactly what makes objects useful shared state with methods that can read and change it.</p>
<h2>How Calling Context Changes <code>this</code></h2>
<p>Here's where most developers get burned. The same function can produce completely different <code>this</code> values depending on <em>how</em> it's called.</p>
<pre><code class="language-js">const user = {
  name: "Riya",
  greet: function() {
    console.log(this.name);
  }
};

user.greet();         // "Riya" — called on user, this = user

const fn = user.greet;
fn();                 // undefined — called alone, this = window
</code></pre>
<p>You didn't change the function. You just changed how you called it. The moment you detach a method from its object, it loses its <code>this</code>.</p>
<p>This catches people constantly especially when passing methods as callbacks:</p>
<pre><code class="language-javascript">const user = {
  name: "Arjun",
  greet: function() {
    console.log("Hello,", this.name);
  }
};

setTimeout(user.greet, 1000); // Hello, undefined 😬
</code></pre>
<p><code>user.greet</code> got handed to <code>setTimeout</code>. When <code>setTimeout</code> calls it, there's no <code>user.</code> in front — so <code>this</code> is lost.</p>
<p>Here's the full picture of how context shifts across four common situations:</p>
<p>For global:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/20cf2a76-a1cc-475e-a0f2-ca10112c06c8.png" alt="" style="display:block;margin:0 auto" />

<p>For Object:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/b851e668-99db-4459-b94b-c69fc37d8906.png" alt="" style="display:block;margin:0 auto" />

<p>Regular Function:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/bc59c12b-8d32-4693-8700-0dc0e9c2a56d.png" alt="" style="display:block;margin:0 auto" />

<p>Arrow Function:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/5fe6726c-8b7d-443c-ab17-2fd979ed3f59.png" alt="" style="display:block;margin:0 auto" />

<h2><code>this</code> Inside Regular Functions</h2>
<p>A standalone function called without any object in front of it follows the global fallback rule.</p>
<pre><code class="language-javascript">function showThis() {
  console.log(this);
}

showThis(); // window (browser) or undefined (strict mode)
</code></pre>
<p>No dot. No owner. Global takes over or <code>undefined</code> in strict mode.</p>
<p><strong>Nested functions lose</strong> <code>this</code> <strong>too:</strong></p>
<pre><code class="language-javascript">const user = {
  name: "Priya",
  greet: function() {
    console.log(this.name); // "Priya" — works fine

    function inner() {
      console.log(this.name); // undefined — inner lost the context
    }
    inner();
  }
};

user.greet();
</code></pre>
<p><code>inner()</code> is called without a dot. Even though it's <em>inside</em> a method, it doesn't inherit <code>this</code>. Each function has its own <code>this</code> determined by how it's called not where it's written.</p>
<h2>The Full Picture</h2>
<p>Here's every context in one place:</p>
<table>
<thead>
<tr>
<th>How it's called</th>
<th>What <code>this</code> is</th>
</tr>
</thead>
<tbody><tr>
<td><code>fn()</code> in global</td>
<td><code>window</code> (or <code>undefined</code> in strict mode)</td>
</tr>
<tr>
<td><code>obj.fn()</code></td>
<td><code>obj</code> — whatever is left of the dot</td>
</tr>
<tr>
<td><a href="http://fn.call"><code>fn.call</code></a><code>(x)</code></td>
<td><code>x</code> — explicitly set</td>
</tr>
<tr>
<td><code>fn.apply(x)</code></td>
<td><code>x</code> — explicitly set</td>
</tr>
<tr>
<td><code>fn.bind(x)()</code></td>
<td><code>x</code> — permanently locked</td>
</tr>
<tr>
<td><code>new fn()</code></td>
<td>the newly created object</td>
</tr>
<tr>
<td>Arrow function</td>
<td><code>this</code> from surrounding scope at definition</td>
</tr>
<tr>
<td>Event listener (regular fn)</td>
<td>the DOM element that fired the event</td>
</tr>
<tr>
<td>Event listener (arrow fn)</td>
<td>outer <code>this</code>, not the element</td>
</tr>
</tbody></table>
<blockquote>
<p>"Programs must be written for people to read, and only incidentally for machines to execute."</p>
<p>--Harold Abelson</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Synchronous vs Asynchronous JavaScript ]]></title><description><![CDATA[You've probably heard these words thrown around. But if someone asked you to explain the difference right now, would you freeze up a little?
Don't worry. By the end of this, it'll feel obvious. Let's ]]></description><link>https://blogs.satpal.cloud/js-sync-vs-async</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-sync-vs-async</guid><category><![CDATA[synchronous javascript]]></category><category><![CDATA[asynchronous JavaScript]]></category><category><![CDATA[Task queue]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Thu, 19 Mar 2026 17:23:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f15fe648-5f7f-4075-854d-87da05989ec3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've probably heard these words thrown around. But if someone asked you to explain the difference right now, would you freeze up a little?</p>
<p>Don't worry. By the end of this, it'll feel obvious. Let's start from zero.</p>
<h2>JavaScript Runs One Line at a Time</h2>
<p>Before we talk about async, you need to understand how JavaScript normally works.</p>
<p>JavaScript is <strong>single-threaded</strong>. That's a fancy way of saying it can only do <em>one thing at a time</em>. It reads your code top to bottom, line by line, finishing each one before moving to the next.</p>
<p>That's synchronous code. And honestly, most of the time it's fine:</p>
<pre><code class="language-javascript">console.log("Step 1 — make coffee");
console.log("Step 2 — open laptop");
console.log("Step 3 — start coding");
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f625d738-bd1b-4cb5-a651-7b06a2e51883.png" alt="" />

<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2ab4549c-d5ec-43b8-aad8-71db2638a036.png" alt="" style="display:block;margin:0 auto" />

<p>No surprises. JavaScript read it top to bottom. Done.</p>
<p>Then what is the problem?</p>
<h2>What If One Step Takes Forever?</h2>
<p>Now imagine step 2 was <em>"wait for the kettle to boil"</em> and that took 4 minutes.</p>
<p>In synchronous world, JavaScript would just… stand there. Frozen. Doing nothing. Waiting. And everything after it your entire app would be on hold too.</p>
<p>That's called <strong>blocking code</strong>. And on the web, it's a disaster.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/838c2167-1ee7-4f7f-97d1-8de3f839d179.png" alt="" style="display:block;margin:0 auto" />

<p>Think about what happens when a website fetches data from a server. That server might be in another country. It might take 2 seconds to respond. If JavaScript just sat there waiting synchronously, your entire page would freeze. No scrolling. No clicking. Nothing. Just a white screen staring back at the user.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0c590c4a-c34d-4ccc-9e52-f64e56c1d36c.png" alt="" style="display:block;margin:0 auto" />

<p>That's why JavaScript needed a way to say: <em>"go do that thing, and come back when you're done an I'll carry on in the meantime."</em></p>
<p>That's <strong>asynchronous code</strong>.</p>
<blockquote>
<p>Js need someone who says:</p>
<p>Tu jaa bhai kaam kar le… main tab tak zindagi sambhaal leta hoon 😌</p>
</blockquote>
<h2>Let's understand what async really mean</h2>
<p>Think of a busy coffee shop.</p>
<p><strong>Synchronous</strong> would be the barista taking one order, making that drink completely, handing it over, <em>then</em> taking the next order. Everyone behind you waits in silence. The queue backs up. It's painful.</p>
<p><strong>Asynchronous</strong> is how real coffee shops work. The barista takes your order, shouts it to the machine, then immediately takes the next person's order. When your drink is ready, they call your name. You collect it. Nobody was blocked waiting for you.</p>
<p>JavaScript works the same way when it's async. It starts a task, sets it aside, keeps going, and comes back when the result is ready.</p>
<h2>Real Life Examples Where You Need Async</h2>
<p>Here are situations where synchronous code would completely break your app:</p>
<ul>
<li><p><strong>Fetching data from an API:</strong> When you call an external server, you have no idea how long it'll take. Could be 200ms, could be 3 seconds. You can't block everything waiting.</p>
</li>
<li><p><strong>Timers:</strong> <code>setTimeout</code> tells JavaScript "do this after 2 seconds." Synchronous JavaScript can't just pause for 2 seconds.</p>
</li>
<li><p><strong>Reading files</strong>: In Node.js, reading a file from disk takes time. You don't want your server frozen while it reads a config file.</p>
</li>
<li><p><strong>User interactions</strong>: You can't predict when a user clicks a button. The code waiting for that click can't block everything else.</p>
</li>
</ul>
<h2>Seeing the Difference in Code</h2>
<p>Here's synchronous code fetching data the kind that would <em>break</em> everything:</p>
<pre><code class="language-javascript">// Imagine this magically waits for the server (it doesn't work like this) 
const data = fetchFromServer(); // ← everything freezes here 
console.log(data); // ← only runs after the wait console.log("This is stuck too");
</code></pre>
<p>Now here's the async version where JavaScript keeps moving:</p>
<pre><code class="language-javascript">fetch('https://api.example.com/data')
  .then(response =&gt; response.json())
  .then(data =&gt; console.log(data)); // ← runs when ready

console.log("This runs immediately, without waiting!"); // ← runs right now
</code></pre>
<h3>Let's Breakdown above example</h3>
<ol>
<li><p>Fetching Starts</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/bdf9b7ee-4a91-41bf-b292-760c25f85573.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>JS keep going</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/3ec52e89-984b-42f1-a72f-3bb302858b11.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>Data arrives</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/186f57c2-7270-4b49-b55d-e6455d10deaf.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>Output Order</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/644531aa-771b-4707-bc32-492ca936b5ca.png" alt="" style="display:block;margin:0 auto" /></li>
</ol>
<h2>The Three Eras of Async JavaScript</h2>
<p>JavaScript didn't always handle async code cleanly. It evolved through three stages and understanding all three matters, because you'll see all of them in real codebases.</p>
<h3>Era 1: Callbacks (The Old Way)</h3>
<p>The original solution was simple: pass a function as an argument, and run it when the job's done.</p>
<pre><code class="language-javascript">setTimeout(function() {
  console.log("2 seconds later...");
}, 2000);
</code></pre>
<p>For simple cases, fine. But the moment you needed to chain several async steps together, things got ugly fast:</p>
<pre><code class="language-javascript">getUser(userId, function(user) {
  getOrders(user.id, function(orders) {
    getOrderDetails(orders[0].id, function(details) {
      sendEmail(details, function(response) {
        console.log("Done... finally");
        // welcome to Callback Hell
      });
    });
  });
});
</code></pre>
<p>This pyramid of doom is called <strong>Callback Hell</strong>. Each step depends on the previous one, and the nesting goes deeper and deeper. Debugging this is miserable. Handling errors in this is worse.</p>
<h3>Era 2: Promises (The Better Way)</h3>
<p>In 2015, JavaScript introduced <strong>Promises,</strong> objects that represent a value that will be available <em>eventually</em>.</p>
<p>A Promise has three states:</p>
<ul>
<li><p><strong>Pending</strong> — still waiting</p>
</li>
<li><p><strong>Fulfilled</strong> — it worked, here's the result</p>
</li>
<li><p><strong>Rejected</strong> — something went wrong</p>
</li>
</ul>
<pre><code class="language-javascript">fetch('https://api.example.com/user')
  .then(response =&gt; response.json())   // fulfilled → transform data
  .then(user =&gt; console.log(user))     // fulfilled → use it
  .catch(error =&gt; console.log(error)); // rejected  → handle error
</code></pre>
<p>Much cleaner. Flat chain instead of a pyramid. Errors handled in one place with <code>.catch()</code>.</p>
<p>But chaining many <code>.then()</code> calls could still feel verbose. So JavaScript went one step further.</p>
<h3>Era 3: Async/Await (The Modern Way)</h3>
<p><code>async/await</code> is just a cleaner way to <em>write</em> Promises. Under the hood it's still Promises — it just looks synchronous, which makes it dramatically easier to read and reason about.</p>
<pre><code class="language-javascript">async function getUser() {
  try {
    const response = await fetch('https://api.example.com/user');
    const user     = await response.json();
    console.log(user);
  } catch (error) {
    console.log("Something went wrong:", error);
  }
}
</code></pre>
<p>The <code>await</code> keyword tells JavaScript: <em>"pause this function here and wait for the Promise to resolve — but don't block the rest of the app."</em></p>
<p>Notice how it reads almost like synchronous code. That's the whole point.</p>
<p><strong>Key rules for async/await:</strong></p>
<ul>
<li><p><code>await</code> can only be used inside a function marked <code>async</code></p>
</li>
<li><p>An <code>async</code> function always returns a Promise, even if you don't write <code>return Promise</code></p>
</li>
<li><p>Errors are handled with normal <code>try/catch</code> — no more <code>.catch()</code> chains</p>
</li>
</ul>
<h2>The Stuff Most Devs Don't Know</h2>
<p>You understand the basics now. Here's where it gets genuinely interesting.</p>
<h3>The Asynchronous Task Queue</h3>
<p>You've seen that JavaScript can come back to async code later. But <em>where</em> does that code go while it's waiting? And <em>who</em> decides when it runs?</p>
<p>That's the job of the task queue system and once you see it, async JavaScript will never feel mysterious again.</p>
<p>There are three players working together at all times.</p>
<p>The <strong>call stack</strong> is where your code actually executes. Every function call goes onto the stack. When it finishes, it pops off. JavaScript can only run one thing at a time here, it's strictly one in, one out.</p>
<p>The <strong>Web APIs</strong> (in the browser) are external helpers that live <em>outside</em> JavaScript. When you call <code>setTimeout</code>, <code>fetch</code>, or add an event listener, JavaScript hands that job off here and immediately moves on. The Web API does the waiting so JavaScript doesn't have to.</p>
<p>The <strong>task queue</strong> (also called the callback queue) is the waiting room. When a Web API finishes its job. The timer expired, the server responded, the user clicked, it puts the callback here. It doesn't jump straight into execution. It waits politely.</p>
<p>The <strong>event loop</strong> is the traffic officer. It runs in a constant loop asking one question: <em>is the call stack empty?</em> The moment it is, it takes the first item from the task queue and pushes it onto the stack.</p>
<p>That's the whole system. Simple in concept, powerful in effect.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/d286b52f-1c7b-4604-a671-86d25e59666a.png" alt="" style="display:block;margin:0 auto" />

<p>Now let's watch it work step by step with real code. This is where it fully clicks.</p>
<p>Example Code</p>
<pre><code class="language-javascript">// the code we are tracing through
console.log("A")
setTimeout(() =&gt; console.log("B"), 0)
console.log("C")
</code></pre>
<p>Lets see how it's work BTS,</p>
<ol>
<li><p>Start</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/d1862337-8a96-43b9-8994-e25110a1b550.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>A logs</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/f748c6b6-4c1f-483f-8599-abe9e8301101.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>setTimeout</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/24a9e23c-94a4-47b1-8647-399fce499338.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>C logs</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2f5169b9-dac7-4da4-9b29-fbd1c5579e87.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>Stack clears</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0de41cc5-607d-47a2-a998-107bd1a79351.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>B logs</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0146b2f7-508e-4903-ad91-c188d1620268.png" alt="" style="display:block;margin:0 auto" />
</li>
<li><p>Output</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/e9ce0d70-dc4e-42e6-bc3d-aa82bf89a6c2.png" alt="" style="display:block;margin:0 auto" /></li>
</ol>
<p>Now here's the part that trips up even experienced developers. There isn't just one queue. There are two and they have different priorities.</p>
<p>The <strong>microtask queue</strong> handles Promises and <code>queueMicrotask</code>. It has higher priority than the regular task queue. After every single task, the event loop drains the <em>entire</em> microtask queue before it picks up the next regular task. Even if a microtask adds another microtask, they all get processed before moving on.</p>
<p>The <strong>macrotask queue</strong> (the regular task queue) handles <code>setTimeout</code>, <code>setInterval</code>, and I/O callbacks. These wait until the microtask queue is completely empty.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/78b264ca-1ddb-4747-8100-905dd698c37e.png" alt="" style="display:block;margin:0 auto" />

<p>This is the full picture of the async task queue system:</p>
<p>The <strong>call stack</strong> runs your code. The <strong>Web APIs</strong> do the waiting. Completed callbacks land in one of two queues</p>
<p>The <strong>microtask queue</strong> for Promises (high priority, drained completely after every task) or the <strong>macrotask queue</strong> for timers and I/O (lower priority, one per turn).</p>
<p>The <strong>event loop</strong> ties it all together, constantly watching the stack and feeding it the next piece of work in the right order.</p>
<p>That two-queue priority is why <code>Promise</code> always beats <code>setTimeout</code>, not because Promises are faster, but because they sit in a queue the event loop checks first. Once you see that, the output order of any async code becomes completely predictable.</p>
<blockquote>
<p><em>"Programs must be written for people to read, and only incidentally for machines to execute."</em></p>
<p>-- Harold Abelson</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[CommonJs Vs EcmaScript Modules]]></title><description><![CDATA[Okay, so you've probably seen words like import, export, and require floating around in JavaScript code and thought what even is this?
Don't worry. By the end of this, it'll click.
Let's start from th]]></description><link>https://blogs.satpal.cloud/cjs-vs-esm</link><guid isPermaLink="true">https://blogs.satpal.cloud/cjs-vs-esm</guid><category><![CDATA[commonjs]]></category><category><![CDATA[require]]></category><category><![CDATA[Export]]></category><category><![CDATA[Import]]></category><category><![CDATA[esm]]></category><category><![CDATA[cjs]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 18 Mar 2026 17:50:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/bf05b898-0e37-45c3-a32d-6f3bda6c5179.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Okay, so you've probably seen words like <code>import</code>, <code>export</code>, and <code>require</code> floating around in JavaScript code and thought <em>what even is this?</em></p>
<p>Don't worry. By the end of this, it'll click.</p>
<p>Let's start from the very beginning.</p>
<h2>Imagine a Classroom With No Desks</h2>
<p>Picture a classroom where every student just throws their stuff on the floor. Books, bags, lunch boxes all mixed together in one giant pile. Now imagine trying to find your pencil in that mess.</p>
<p>That's literally what early JavaScript was like.</p>
<p>Every file you wrote dumped its variables into one shared space called the <strong>global scope</strong>. And here's where it got ugly — if two files used the same variable name, the second one would just wipe out the first. No warning. No error. Just silent, confusing chaos.</p>
<p>Say you had two files:</p>
<p>Example:</p>
<p><a class="embed-card" href="https://codepen.io/editor/Satpalsinh-Rana/pen/019cfcc2-89a6-780a-bc59-8ecb8f458177">https://codepen.io/editor/Satpalsinh-Rana/pen/019cfcc2-89a6-780a-bc59-8ecb8f458177</a></p>

<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/6990f58b-7ca5-4926-a514-23a675334df2.png" alt="" style="display:block;margin:0 auto" />

<p>If both are loaded on the same page, <code>price</code> is now <code>0</code>. Your cart logic just got quietly destroyed by your checkout file. Fun times.</p>
<h2>The Fix: Give Every File Its Own Room</h2>
<p>This is exactly what <strong>modules</strong> do. A module is just a JavaScript file that keeps its variables <em>to itself</em>. Nothing leaks out accidentally. If you want another file to use something, you have to deliberately <strong>export</strong> it. And the other file has to deliberately <strong>import</strong> it.</p>
<p>It's like going from that messy floor to everyone having their own desk with a locked drawer. You only share what you choose to share.</p>
<p>Simple idea. Huge difference.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/0ca1c041-74da-45a9-8ee0-2646636b362f.png" alt="" style="display:block;margin:0 auto" />

<h2>Two Ways JavaScript Does This</h2>
<p>There are two main module systems you'll come across. Don't let that scare you — they do the same thing, just with slightly different styles.</p>
<h3>CommonJS — The Old School Way</h3>
<p>This one was invented for <strong>Node.js</strong> (JavaScript on the server). You'll see it a lot in older projects and tutorials.</p>
<p>It uses two things:</p>
<ul>
<li><p><code>module.exports</code> — to send something out</p>
</li>
<li><p><code>require()</code> — to bring something in</p>
</li>
</ul>
<h3><strong>Sending code out:</strong></h3>
<pre><code class="language-javascript">// greet.js
const sayHello = (name) =&gt; {
  console.log("Hello, " + name + "!");
};

module.exports = { sayHello };
</code></pre>
<p><strong>Bringing it in:</strong></p>
<pre><code class="language-javascript">const { sayHello } = require('./greet.js');
sayHello("Riya"); // Hello, Riya!
</code></pre>
<p>That's really it. You wrap your stuff in <code>module.exports</code>, and you grab it with <code>require()</code>.</p>
<p>You might see people write <code>exports.sayHello = ...</code> as a shortcut. It mostly works, but the moment you do <code>exports = { sayHello }</code>, it breaks. Stick to <code>module.exports</code> when you're starting out. Way less confusing.</p>
<h3>ES Modules — The Modern Way</h3>
<p>In 2015, JavaScript introduced a cleaner, more modern system called <strong>ES Modules</strong>. This is what most tutorials and frameworks use today, and it's what you should focus on learning.</p>
<p>Instead of <code>require</code> and <code>module.exports</code>, you use <code>import</code> and <code>export</code>. Much more readable.</p>
<p><strong>Named Exports sharing multiple things</strong></p>
<pre><code class="language-javascript">// math.js
export const add = (a, b) =&gt; a + b;
export const PI = 3.14;
</code></pre>
<pre><code class="language-javascript">// main.js
import { add, PI } from './math.js';
console.log(add(2, PI)); // 5.14
</code></pre>
<p>Notice the curly braces <code>{}</code> in the import? That tells JavaScript <em>exactly</em> which piece you want.</p>
<p><strong>Default Export — when a file has one main thing</strong></p>
<pre><code class="language-javascript">// User.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}
</code></pre>
<pre><code class="language-javascript">// main.js
import User from './User.js'; // No curly braces needed!
const me = new User("Arjun");
</code></pre>
<p>No curly braces here because there's only one default thing JavaScript already knows what you mean.</p>
<p><strong>Seeing both together</strong></p>
<p>If you've ever used React, you've already seen this in action:</p>
<pre><code class="language-js">import React, { useState, useEffect } from 'react';
</code></pre>
<ul>
<li><p><code>React</code> → default export (no braces)</p>
</li>
<li><p><code>useState</code>, <code>useEffect</code> → named exports (inside braces)</p>
</li>
</ul>
<p>Once you get that distinction, a <em>lot</em> of code starts making sense.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/a511a07b-0242-4f7c-86ce-177beb69f47b.png" alt="" style="display:block;margin:0 auto" />

<h2>So What Should You Actually Use?</h2>
<p>If you're just starting out go with ES Modules. It's cleaner to read, it's the modern standard, and every major framework (React, Vue, Svelte) uses it.</p>
<p>You'll run into CommonJS eventually, especially in older Node.js code. But now that you understand the why behind modules, picking up either syntax is just a matter of remembering a few keywords.</p>
<h2>Okay, You've Got the Basics now Let's Go Deeper</h2>
<p>So you understand what modules are and how <code>import</code>/<code>export</code> works. Great. But here's the thing CJS and ESM aren't just different syntaxes. Under the hood, they behave very differently. And those differences actually matter when you're building real apps.</p>
<p>Let's talk about the stuff most tutorials skip.</p>
<h2>How They Actually Load Files</h2>
<p>This is one of the biggest differences, and it affects performance.</p>
<p><strong>CommonJS is synchronous.</strong> When Node.js hits a <code>require()</code>, it stops everything, reads the entire file, executes it, and then moves on. It's like stopping your car completely every time you need to check the map.</p>
<pre><code class="language-javascript">const data = require('./heavyFile.js'); // Everything pauses here
console.log("This runs AFTER the file loads");
</code></pre>
<p>This works fine on a server where files live on your hard drive and load in milliseconds. But it's a disaster for browsers, where files travel over a network and could take seconds.</p>
<p><strong>ES Modules are asynchronous.</strong> The browser (or Node.js) can <em>start</em> fetching multiple modules at the same time without blocking everything else. Your app stays responsive while the files load in the background.</p>
<p>This is a big reason why ESM became the standard for the web.</p>
<h2>Static vs Dynamic</h2>
<p>This is where it gets really interesting, and most beginners never hear about it.</p>
<p><strong>CommonJS is dynamic.</strong> The <code>require()</code> call can live <em>anywhere</em> in your code inside an <code>if</code> statement, inside a function, even based on user input:</p>
<pre><code class="language-javascript">// This is totally valid CJS
if (userRole === "admin") {
  const adminTools = require('./adminTools.js');
}
</code></pre>
<p>Sounds flexible, right? But here's the problem because the module path can be a variable, JavaScript has no idea what's being imported until the code actually <em>runs</em>. That means:</p>
<ul>
<li><p>Bundlers can't tree-shake (remove unused code)</p>
</li>
<li><p>Security scanners can't see what's being loaded</p>
</li>
<li><p>A bad actor could potentially manipulate what gets required</p>
</li>
</ul>
<p>Imagine this nightmare scenario:</p>
<pre><code class="language-javascript">const userInput = getInputFromSomewhere();
const module = require(userInput); // What is this loading?
</code></pre>
<p>If that <code>userInput</code> somehow comes from an untrusted source, you've got a serious security hole.</p>
<p><strong>ES Modules are static.</strong> Every <code>import</code> statement must sit at the top of the file with a fixed path no variables, no conditions, no surprises:</p>
<pre><code class="language-javascript">// This is NOT allowed in ESM
if (condition) {
  import something from './file.js'; // Syntax error
}
</code></pre>
<p>That might feel restrictive, but it's actually a feature. Because the structure is fixed and predictable, tools can analyze your entire dependency tree <em>before</em> running anything. Security scanners know exactly what your app loads. Bundlers can eliminate dead code with confidence. Everything is transparent.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/fe39117f-3c48-433d-ae6d-2238a3412132.png" alt="" style="display:block;margin:0 auto" />

<h2>Live Bindings vs Copied Values</h2>
<p>This one is subtle but genuinely catches developers off guard.</p>
<p><strong>CJS gives you a copy</strong> of the exported value at the time of import. If that value changes later in the original file, your copy doesn't update.</p>
<pre><code class="language-typescript">// counter.cjs
let count = 0;
module.exports = { count, increment: () =&gt; count++ };

// main.cjs
const { count, increment } = require('./counter.cjs');
increment();
console.log(count); // Still 0 — you got a copy, not the real thing
</code></pre>
<p><strong>ESM gives you a live binding</strong>. A live connection to the actual variable in the original file. If it changes, you see the change.</p>
<pre><code class="language-javascript">// counter.js
export let count = 0;
export const increment = () =&gt; count++;

// main.js
import { count, increment } from './counter.js';
increment();
console.log(count); // 1 — it updated!
</code></pre>
<p>This matters a lot when you're working with shared state, counters, flags, or anything that changes over time.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/3c6ac652-7596-4916-8ebb-9b7f6365cbc0.png" alt="" style="display:block;margin:0 auto" />

<h2>A Quick Side-by-Side to Tie It All Together</h2>
<table>
<thead>
<tr>
<th></th>
<th>CommonJS (CJS)</th>
<th>ES Modules (ESM)</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Syntax</strong></td>
<td><code>require</code> / <code>module.exports</code></td>
<td><code>import</code> / <code>export</code></td>
</tr>
<tr>
<td><strong>Loading</strong></td>
<td>Synchronous (blocking)</td>
<td>Asynchronous (non-blocking)</td>
</tr>
<tr>
<td><strong>Analysis</strong></td>
<td>Dynamic (runtime)</td>
<td>Static (before runtime)</td>
</tr>
<tr>
<td><strong>Tree Shaking</strong></td>
<td>Limited</td>
<td>Full support</td>
</tr>
<tr>
<td><strong>Security</strong></td>
<td>Riskier with dynamic paths</td>
<td>Safer — paths are fixed</td>
</tr>
<tr>
<td><strong>Circular deps</strong></td>
<td>Silent broken values</td>
<td>Handled more gracefully</td>
</tr>
<tr>
<td><strong>Exported values</strong></td>
<td>Copied at import time</td>
<td>Live bindings</td>
</tr>
<tr>
<td><strong>Best for</strong></td>
<td>Legacy Node.js code</td>
<td>Modern apps and browsers</td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/af655c22-ac46-4b31-9252-762ac5f61d25.png" alt="" style="display:block;margin:0 auto" />

<blockquote>
<p><em>"The secret to building large apps is never build large apps. Break your applications into small pieces. Then assemble those testable, bite-sized pieces into your big application."</em> — <strong>Justin Meyer</strong></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[The Magic of this, call(), apply(), and bind() in JavaScript]]></title><description><![CDATA[this
The simplest way to think about this is: "Who is calling the function?"
It is a keyword that refers to the context (the object) that is currently executing the code. It acts like a pronoun in Eng]]></description><link>https://blogs.satpal.cloud/js-this</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-this</guid><category><![CDATA[call]]></category><category><![CDATA[apply]]></category><category><![CDATA[Bind]]></category><category><![CDATA[this]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Sun, 15 Mar 2026 15:13:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/25f45800-3c4d-4843-8741-e1373e8c2d1b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>this</h2>
<p>The simplest way to think about <code>this</code> is: <strong>"Who is calling the function?"</strong></p>
<p>It is a keyword that refers to the <strong>context</strong> (the object) that is currently executing the code. It acts like a pronoun in English instead of saying "Satpal is coding", you say "He is coding."</p>
<h3><code>this</code> inside Objects</h3>
<p>When you use <code>this</code> inside a method of an object, it refers to the object itself.</p>
<pre><code class="language-javascript">const dev = {
  name: "Satpal",
  greet: function() {
    console.log(`Hi, I am ${this.name}`);
  }
};

dev.greet(); 
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/8469c4b6-373f-49a9-ac49-ca36afce71cd.png" alt="" style="display:block;margin:0 auto" />

<p><em>Here,</em> <code>this</code> <em>is</em> <code>dev</code> <em>because</em> <code>dev</code> <em>is the one calling</em> <code>greet()</code><em>.</em></p>
<h3><code>this</code> inside Normal Functions</h3>
<p>In a regular function (not a method of an object), <code>this</code> defaults to the <strong>Global Object</strong> (<code>window</code> in browsers). If you use <code>strict mode</code>, it will be <code>undefined</code>.</p>
<h2>Controlling <code>this</code>: Call, Apply, and Bind</h2>
<p>Sometimes, you want to borrow a method from one object and use it with another. This is where <code>call</code>, <code>apply</code>, and <code>bind</code> come in.</p>
<h3><code>call()</code></h3>
<p>Calls a function immediately and allows you to pass in the <code>this</code> context explicitly, followed by arguments one by one.</p>
<pre><code class="language-javascript">function intro(city, tech) {
  console.log(`\({this.name} from \){city} loves ${tech}.`);
}

const user = { name: "Satpal" };
intro.call(user, "Ahmedabad", "Angular"); 
// Output: Satpal from Ahmedabad loves Angular.
</code></pre>
<h3><code>apply()</code></h3>
<p>Exactly like <code>call()</code>, but it takes arguments as an <strong>Array</strong>. <em>Mnemonic:</em> <em><strong>A</strong></em><em>pply =</em> <em><strong>A</strong></em><em>rray.</em></p>
<pre><code class="language-javascript">intro.apply(user, ["Ahmedabad", "NodeJS"]);
</code></pre>
<h3><code>bind()</code></h3>
<p>Instead of calling the function immediately, <code>bind()</code> <strong>returns a new function</strong> with the <code>this</code> context fixed. You can call it later.</p>
<pre><code class="language-typescript">const boundIntro = intro.bind(user, "Ahmedabad", "TypeScript");
boundIntro(); // Calls the function later
</code></pre>
<table style="min-width:100px"><colgroup><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col><col style="min-width:25px"></col></colgroup><tbody><tr><td><p><strong>Method</strong></p></td><td><p><strong>Invocation</strong></p></td><td><p><strong>Arguments</strong></p></td><td><p><strong>Returns</strong></p></td></tr><tr><td><p><code>call()</code></p></td><td><p>Immediate</p></td><td><p>Comma-separated</p></td><td><p>Result of function</p></td></tr><tr><td><p><code>apply()</code></p></td><td><p>Immediate</p></td><td><p>Array <code>[]</code></p></td><td><p>Result of function</p></td></tr><tr><td><p><code>bind()</code></p></td><td><p>Later</p></td><td><p>Comma-separated</p></td><td><p>A new function</p></td></tr></tbody></table>

<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/99bcb842-c08e-4594-9ccd-f871a89dd074.png" alt="" style="display:block;margin:0 auto" />

<p>Example</p>
<pre><code class="language-typescript">const laptop = {
  brand: "MacBook",
  showInfo: function(ram, storage) {
    console.log(`\({this.brand} with \){ram}GB RAM and ${storage}GB SSD`);
  }
};

const desktop = { brand: "Custom PC" };

// 1. Borrowing with call()
laptop.showInfo.call(desktop, 32, 1024);

// 2. Borrowing with apply()
laptop.showInfo.apply(desktop, [16, 512]);

// 3. Storing with bind()
const showDesktop = laptop.showInfo.bind(desktop);
showDesktop(64, 2048);
</code></pre>
<p>Understanding <code>this</code> is what separates a beginner from an intermediate JavaScript developer. While <code>this</code> can seem "magical", it always follows the simple rule: <strong>look at what is to the left of the dot when the function is called.</strong></p>
<h3><strong>Let's Connect! 🚀</strong></h3>
<p>I’m currently deep-diving into the <strong>JavaScript</strong>, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!</p>
<ul>
<li><p><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/satpalsinhrana"><strong>Satpalsinh's Profile</strong></a></p>
</li>
<li><p><strong>Follow my Blog:</strong> <a href="http://blogs.satpal.cloud"><strong>blogs.satpal.cloud</strong></a></p>
</li>
</ul>
<p><strong>Keep coding and keep building.</strong></p>
]]></content:encoded></item><item><title><![CDATA[OOP in JavaScript]]></title><description><![CDATA[Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. Think of it as a way to model real-world things in ]]></description><link>https://blogs.satpal.cloud/js-oop</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-oop</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Sun, 15 Mar 2026 14:35:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/57fb3a65-73d4-4663-b2a6-67f3b680cfb3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Object-Oriented Programming (OOP) is a <strong>programming paradigm</strong> that organizes software design around <strong>data</strong>, or objects, rather than functions and logic. Think of it as a way to model real-world things in your code.</p>
<h2>Why ?</h2>
<p>Imagine you are a car manufacturer. You don’t just start building a car from scratch every time. Instead, you create a <strong>blueprint</strong>. This blueprint defines the features (color, engine) and actions (drive, brake).</p>
<ul>
<li><p><strong>The Blueprint</strong> is the <strong>Class</strong>.</p>
</li>
<li><p><strong>The Physical Car</strong> on the road is the <strong>Object</strong> (or Instance).</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2448bb99-0c7c-49d0-a51d-5412e57cb5bd.png" alt="" style="display:block;margin:0 auto" />

<h2>What is a Class in JavaScript?</h2>
<p>Introduced in ES6, a <code>class</code> is a template for creating objects. It encapsulates data (properties) and behavior (methods) into a single unit, promoting <strong>code reusability</strong>.</p>
<p>Let’s look at how to translate that blueprint into JavaScript code.</p>
<pre><code class="language-javascript">class Car {
  // The Constructor: The "Setup" function
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
  }

  // A Method: Defining behavior
  drive() {
    console.log(`The \({this.color} \){this.brand} is now driving!`);
  }
}

// Instantiating Objects (Creating cars from the blueprint)
const myCar = new Car("Tesla", "Model 3", "White");
const friendsCar = new Car("Tata", "Nexon", "Blue");

myCar.drive(); // Output: The White Tesla is now driving!
</code></pre>
<h2>Breakdown</h2>
<ul>
<li><p><strong>The Constructor Method:</strong> This is a special method that runs automatically when you create a new object. It’s where you initialize the object's properties using the <code>this</code> keyword.</p>
</li>
<li><p><strong>Methods:</strong> These are functions defined inside the class that describe what the object can <em>do</em>.</p>
</li>
<li><p><strong>Encapsulation (The Basics):</strong> This is the practice of "bundling" the data and the methods that operate on that data within one unit (the class). It keeps the code organized and prevents outside code from accidentally messing with the internal logic.</p>
</li>
</ul>
<h3>Example - The Student Class</h3>
<pre><code class="language-javascript">class Student {
  constructor(name, age, course) {
    this.name = name;
    this.age = age;
    this.course = course;
  }

  // Method to display details
  displayDetails() {
    console.log(`Student: \({this.name}, Age: \){this.age}, Course: ${this.course}`);
  }
}

// Creating multiple student objects
const student1 = new Student("Satpal", 24, "Full Stack Development");
const student2 = new Student("Aman", 22, "Data Science");

student1.displayDetails();
student2.displayDetails();
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/3001c06c-41fc-4830-bced-3d6a764fbc95.png" alt="" style="display:block;margin:0 auto" />

<h2>The Four Pillars of OOP</h2>
<h3>Encapsulation (Data Hiding)</h3>
<p>Encapsulation is about keeping the internal state of an object private and only exposing what is necessary through a public interface. In modern JavaScript (ES2022+), we use the <code>#</code> prefix for truly private fields.</p>
<pre><code class="language-javascript">class BankAccount {
  #balance = 0; // Private field

  deposit(amount) {
    if (amount &gt; 0) this.#balance += amount;
  }

  getBalance() {
    return `Your balance is ₹${this.#balance}`;
  }
}

const myAcc = new BankAccount();
myAcc.deposit(500);
console.log(myAcc.#balance); // Error: Private field '#balance' must be declared in an enclosing class
</code></pre>
<h3>Abstraction (Complexity Hiding)</h3>
<p>Abstraction means showing only the essential features of an object and hiding the "how it works" logic. You may know how to use a <code>fetch()</code> call in your Angular app/ React App, but you don't need to know the low-level TCP/IP handshake logic happening in the background.</p>
<h3>Inheritance (Hierarchy)</h3>
<p>Inheritance allows one class to derive properties and methods from another. In JS, we use <code>extends</code> and <code>super()</code>.</p>
<pre><code class="language-javascript">class User {
  constructor(username) {
    this.username = username;
  }
  logIn() { console.log(`${this.username} logged in.`); }
}

class Admin extends User {
  deleteUser(user) { console.log(`Admin deleted ${user}`); }
}
</code></pre>
<h3>Polymorphism (Many Forms)</h3>
<p>Polymorphism allows different classes to be treated as instances of the same parent class through the same interface, but each responds in its own way.</p>
<pre><code class="language-javascript">class Shape {
  draw() { console.log("Drawing a shape..."); }
}

class Circle extends Shape {
  draw() { console.log("Drawing a circle ⭕"); } // Overriding
}
</code></pre>
<h2>Prototypal Inheritance:</h2>
<p>Unlike Classical OOP (C++/Java), JavaScript uses <strong>Prototypal Inheritance</strong>. Every object in JS has a hidden property called <code>[[Prototype]]</code> (accessible via <code>__proto__</code>).</p>
<ul>
<li><p>When you call a method on an object, JS first looks at the object itself.</p>
</li>
<li><p>If it doesn't find it, it looks at the object's <strong>Prototype</strong>.</p>
</li>
<li><p>It keeps going up the "Prototype Chain" until it reaches <code>null</code>.</p>
</li>
</ul>
<p>By using Classes and the Four Pillars (Encapsulation, Abstraction, Inheritance, and Polymorphism), you ensure that your code is:</p>
<ol>
<li><p><strong>Maintainable:</strong> Changes in one class don't break the whole app.</p>
</li>
<li><p><strong>Scalable:</strong> Adding new features becomes a matter of extending existing logic.</p>
</li>
<li><p><strong>Readable:</strong> Your code tells a story about real-world objects.</p>
</li>
</ol>
<h3><strong>Let's Connect! 🚀</strong></h3>
<p>I’m currently deep-diving into the <strong>JavaScript</strong>, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!</p>
<ul>
<li><p><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/satpalsinhrana"><strong>Satpalsinh's Profile</strong></a></p>
</li>
<li><p><strong>Follow my Blog:</strong> <a href="http://blogs.satpal.cloud"><strong>blogs.satpal.cloud</strong></a></p>
</li>
</ul>
<p><strong>Keep coding and keep building.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Objects in JavaScript]]></title><description><![CDATA[If you are working with JS and you when you have to deal with complex structured data. That’s where Objects come in.
What Are Objects and Why Do We Need Them?
Imagine you want to store information abo]]></description><link>https://blogs.satpal.cloud/js-objects</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-objects</guid><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Sun, 15 Mar 2026 10:50:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/a58af905-4082-4bfd-a247-6692ec905f92.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are working with JS and you when you have to deal with complex structured data. That’s where <strong>Objects</strong> come in.</p>
<h2>What Are Objects and Why Do We Need Them?</h2>
<p>Imagine you want to store information about a person. Using basic variables, your code would look like this:</p>
<pre><code class="language-javascript">let personName = "Alex";
let personAge = 25;
let personCity = "London";
</code></pre>
<p>This works, but it’s messy. These variables are floating around independently. If you add 10 more people, your code becomes a nightmare to manage.</p>
<h2>Object</h2>
<p>An Object solves this by grouping related data together into a single, organized structure. Think of an object like a real-world dictionary: you look up a word (the key) to find its definition (the value).</p>
<p>In JavaScript, objects are collections of these <strong>key-value pairs</strong>.</p>
<h2>Array vs. Object: What’s the Difference?</h2>
<p>You might be wondering, "Can't I just use an array?"</p>
<p>You can, but it’s not always the right tool for the job.</p>
<ul>
<li><p><strong>Arrays</strong> are for <em>ordered</em> lists of data. You access items using their numbered index (<code>array[0]</code>). Use arrays when the order matters (e.g., a list of top 10 movies).</p>
</li>
<li><p><strong>Objects</strong> are for <em>labeled</em> data. You access items using their specific name (<code>object.name</code>). Use objects when you have a single entity with descriptive properties.</p>
</li>
</ul>
<h2>Create Object</h2>
<p>Creating an object is incredibly straightforward. We use curly braces <code>{}</code> to define it, and inside, we separate our keys and values with a colon <code>:</code>.</p>
<pre><code class="language-javascript">const person = {
  name: "Alex",
  age: 25,
  city: "London"
};

console.log(person);
</code></pre>
<h2>Access Data inside Object</h2>
<p>Now that we have our object, how do we read the data inside it? You have two main tools in your belt: Dot Notation and Bracket Notation.</p>
<h3><strong>Dot Notation (The everyday choice):</strong></h3>
<p>This is the cleanest and most common way to grab a value.</p>
<pre><code class="language-javascript">console.log(person.name); // Output: "Alex"
</code></pre>
<h3><strong>Bracket Notation (The flexible choice):</strong></h3>
<p>You use brackets when your key has a space in it (which isn't recommended, but happens), or when you are using a variable to look up a key dynamically.</p>
<pre><code class="language-javascript">console.log(person["city"]); // Output: "London"

// Dynamic lookup example:
let query = "age";
console.log(person[query]); // Output: 25
</code></pre>
<h2>Updating Object Properties</h2>
<p>Objects are mutable, meaning you can change their data even after they are created (yes, even if you used <code>const</code>).</p>
<pre><code class="language-javascript">// Alex had a birthday
person.age = 26; 

// Alex moved to a new city
person["city"] = "Manchester";

console.log(person.age); // Output: 26
</code></pre>
<h2>Adding and Deleting Properties</h2>
<p>JavaScript objects are incredibly flexible. You can add new properties on the fly, or delete them if they are no longer needed.</p>
<p>Add</p>
<pre><code class="language-javascript">person.profession = "Software Developer";
console.log(person.profession); // Output: "Software Developer"
</code></pre>
<p>Delete</p>
<pre><code class="language-javascript">delete person.city;
console.log(person.city); // Output: undefined
</code></pre>
<h2>Looping Through Object Keys</h2>
<p>Sometimes you need to read every single piece of data inside an object, but you don't know the keys in advance. To do this, we use a special loop called the <code>for...in</code> loop.</p>
<pre><code class="language-javascript">
const car = {
  brand: "Tesla",
  model: "Model 3",
  year: 2023
};

for (let key in car) {
  // We use bracket notation here because 'key' is a variable!
  console.log(`\({key}: \){car[key]}`); 
}

// Output:
// brand: Tesla
// model: Model 3
// year: 2023
</code></pre>
<h2>Deep Dive in object</h2>
<h3>All ways to create object</h3>
<p><strong>The Object Literal (The Daily Driver)</strong></p>
<p>As mentioned above, this is the standard, easiest way to create an object. You will use this 95% of the time.</p>
<pre><code class="language-javascript">const user = {
  name: "Alex",
  role: "Developer"
};
</code></pre>
<p><strong>The</strong> <code>new Object()</code> <strong>Constructor</strong></p>
<p>This uses JavaScript's built-in Object constructor. It does the exact same thing as the literal, but it's more verbose. It's rarely used in modern code.</p>
<pre><code class="language-javascript">const user = new Object();
user.name = "Alex";
user.role = "Developer";
</code></pre>
<p><code>Object.create()</code> <strong>(For Prototypal Inheritance)</strong></p>
<p>This is a powerful method. It creates a brand new object, but allows you to choose an existing object to act as its "prototype" (blueprint).</p>
<pre><code class="language-javascript">const vehiclePrototype = { wheels: 4 };
const car = Object.create(vehiclePrototype);

car.brand = "Tesla";
console.log(car.wheels); // Output: 4 (Inherited from the prototype!)
</code></pre>
<p><strong>Constructor Functions (The Old-School Blueprint)</strong></p>
<p>Before modern classes existed, developers used normal functions with the <code>new</code> keyword to create multiple instances of an object.</p>
<pre><code class="language-javascript">function User(name, role) {
  this.name = name;
  this.role = role;
}
const user1 = new User("Alex", "Developer");
</code></pre>
<p><strong>ES6 Classes (The Modern Blueprint)</strong></p>
<p>Introduced in 2015, this provides a cleaner, more readable syntax for creating object blueprints. Under the hood, it works exactly like the Constructor Function above.</p>
<pre><code class="language-javascript">class UserClass {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }
}
const user2 = new UserClass("Sam", "Designer");
</code></pre>
<h3>Important methods on objects</h3>
<p>JavaScript provides a static <code>Object</code> utility with several incredibly useful methods. If you are manipulating data, you will use these constantly.</p>
<pre><code class="language-javascript">const laptop = { brand: "Apple", model: "MacBook Pro", year: 2023 };
</code></pre>
<ul>
<li><p><code>Object.keys(obj)</code>: Returns an array of the object's keys.</p>
<pre><code class="language-javascript">console.log(Object.keys(laptop)); // ["brand", "model", "year"]
</code></pre>
</li>
<li><p><code>Object.values(obj)</code>: Returns an array of the object's values.</p>
<pre><code class="language-javascript">console.log(Object.values(laptop)); // ["Apple", "MacBook Pro", 2023]
</code></pre>
</li>
<li><p><code>Object.entries(obj)</code>: Returns an array of arrays, each containing a [key, value] pair. This is amazing for looping!</p>
<pre><code class="language-javascript">console.log(Object.entries(laptop)); 
// [["brand", "Apple"], ["model", "MacBook Pro"], ["year", 2023]]
</code></pre>
</li>
<li><p><code>Object.freeze(obj)</code>: Completely locks an object. You cannot add, delete, or change <em>any</em> properties.</p>
</li>
<li><p><code>Object.seal(obj)</code>: Partially locks an object. You cannot add or delete properties, but you <em>can</em> update existing ones.</p>
</li>
</ul>
<h3>Deep Copy vs Shallow Copy</h3>
<p>This is a core concept that trips up almost every JavaScript developer at some point.</p>
<p>In JavaScript, primitive types (strings, numbers) are passed by <strong>value</strong>. But Objects are passed by <strong>reference</strong>. When you assign an object to a new variable, you aren't copying the data; you are just copying the <em>memory address</em> pointing to that data.</p>
<h2>The Shallow Copy</h2>
<p>A shallow copy creates a new object and copies the <em>top-level</em> properties over. However, if your object has a nested object inside it, that nested object still shares the same memory reference!</p>
<p><strong>How to make a shallow copy:</strong> You can use the Spread Operator (<code>...</code>) or <code>Object.assign()</code>.</p>
<pre><code class="language-javascript">const original = {
  name: "Alex",
  skills: { language: "JavaScript" } // This is a nested object
};

// Create a shallow copy using the spread operator
const shallowCopy = { ...original };

// Let's change the top-level property
shallowCopy.name = "Sam"; 
console.log(original.name); // "Alex" (Safe! Top-level is copied)

// BUT, let's change the nested property
shallowCopy.skills.language = "TypeScript";
console.log(original.skills.language); // "TypeScript" (Wait, the original changed too?!)
</code></pre>
<p>because it was a shallow copy, both objects are sharing the exact same <code>skills</code> object in memory.</p>
<h2><strong>The Deep Copy</strong></h2>
<p>A deep copy creates a completely independent clone. Every nested object is duplicated into a brand new memory space. Changing the clone will <em>never</em> affect the original.</p>
<p><strong>How to make a deep clone:</strong></p>
<p><strong>1. The Modern Way:</strong> <code>structuredClone()</code><br />This is a built-in feature in modern JavaScript (available in browsers and Node.js). It is currently the absolute best and cleanest way to deep clone an object.</p>
<p><strong>JavaScript</strong></p>
<pre><code class="language-plaintext">const deepCopy = structuredClone(original);

deepCopy.skills.language = "Python";
console.log(original.skills.language); // "TypeScript" (The original is perfectly safe!)
</code></pre>
<p><strong>2. The Old Hack:</strong> <code>JSON.parse(JSON.stringify())</code><br />Before <code>structuredClone()</code> existed, developers used this trick. It converts the object into a text string, and then parses it back into a brand new object.</p>
<ul>
<li><em>Warning:</em> This method breaks if your object contains Functions, <code>Date</code> objects, or <code>undefined</code> values, as JSON doesn't support them.</li>
</ul>
<p><strong>3. The Library Way: Lodash</strong><br />If you are working in a massive enterprise codebase, you might see <code>_.cloneDeep(obj)</code> from the Lodash library being used to safely handle complex cloning.</p>
]]></content:encoded></item><item><title><![CDATA[Arrow Functions in JavaScript]]></title><description><![CDATA[Before knowing what arrow functions does and why it was introduced. Let's understand what function expression is.
Function Expression
It means to use function keyword and define a function inside an e]]></description><link>https://blogs.satpal.cloud/js-arrow-functions</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-arrow-functions</guid><category><![CDATA[#arrowfunction]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Sat, 14 Mar 2026 18:15:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/2317c597-6072-41eb-81ce-947b26d25e45.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before knowing what arrow functions does and why it was introduced. Let's understand what function expression is.</p>
<h3>Function Expression</h3>
<p>It means to use <code>function</code> keyword and define a function inside an expression. In simple words, previously folk use to write and assign function to variable as below,</p>
<pre><code class="language-javascript">const ctc = function (base, variable) { return base +  variable; };

console.log(ctc(30000, 40000));
</code></pre>
<h2>Arrow Functions</h2>
<p>So, Arrow Functions are used to create a arrow function expression. An alternate to traditional approach mentioned above.</p>
<p>Example</p>
<pre><code class="language-javascript">const ctc = (base, variable) =&gt; base + variable;

console.log(ctc(30000, 40000)); 
</code></pre>
<p>But, it has it's own behavior</p>
<ul>
<li><p>They don't have their own binding and should not be used as methods.</p>
</li>
<li><p>We cannot use them as constructor</p>
</li>
<li><p>It cannot use yield within their body and cannot be used as generators.</p>
</li>
</ul>
<h3>No own bindings to <code>this</code>, <code>arguments</code>, or <code>super</code></h3>
<p>Regular functions are dynamic. So the value of <code>this</code> depends on <strong>how</strong> the function is called. If an object calls a method, <code>this</code> refers to that object.</p>
<p>Arrow functions are lexical. They do not create their own <code>this</code> context. Instead, they inherit <code>this</code> from the surrounding scope where they were defined (like looking up to their parent block).</p>
<p>Imagine the Great Hall of Winterfell (the <strong>Parent Scope</strong>). Lord Eddard Stark is organizing his forces. He sends two warriors south to the Red Keep (the <strong>Object</strong>) to serve the Crown.</p>
<ul>
<li><p><strong>The Sellsword / Regular Function (Bronn):</strong> Bronn's loyalty is <em>dynamic</em>. It depends entirely on who is currently paying him right now. When Cersei Lannister at the Red Keep issues a command and asks, "Who do you fight for?", Bronn looks around at his current employer and says, <em>"I fight for House Lannister."</em> (<code>this</code> = the object that called the method).</p>
</li>
<li><p><strong>The Loyal Bannerman / Arrow Function (Arya Stark):</strong> Arya's loyalty is <em>lexical</em>. Her allegiance was permanently forged in Winterfell the moment she was born. Even though she is physically standing in the Red Keep, and Cersei is the one issuing the command, Arya completely ignores her current surroundings. When asked, "Who do you fight for?", she looks back to her origins and says, <em>"I fight for House Stark."</em> (<code>this</code> = the parent scope where she was created).</p>
</li>
</ul>
<p>Example</p>
<pre><code class="language-javascript">const winterfell = {
  houseName: "Stark",

  sendWarriorsSouth: function() {

    const redKeep = {
      houseName: "Lannister",
      
      bronn: function() {
        console.log(`Bronn says: I fight for House ${this.houseName}`);
      },

      arya: () =&gt; {
        console.log(`Arya says: I fight for House ${this.houseName}`);
      }
    };

    redKeep.bronn(); 
    redKeep.arya();  
  }
};

winterfell.sendWarriorsSouth();

// Output:
// Bronn says: I fight for House Lannister
// Arya says: I fight for House Stark
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/7a089054-46c3-4c39-b1d2-821ec56857da.png" alt="" />

<p>Note: Generally arrow function are not use in methods, because object methods usually need to talk to the object they live inside, and arrow functions are physically incapable of doing that.</p>
<h3>Cannot be used as constructors</h3>
<p>In JavaScript, regular functions can be used to create blueprints for new objects using the <code>new</code> keyword. When you call <code>new RegularFunction()</code>, JavaScript creates a brand new object, binds <code>this</code> to that new object, and links it to the function's prototype.</p>
<p>Arrow functions were designed to be lightweight and fast. To save memory and execution time, JavaScript engines completely removed the <code>.prototype</code> property from arrow functions. Without a prototype, and without the ability to bind a new <code>this</code>, they simply cannot construct objects.</p>
<p>Regular Function:</p>
<pre><code class="language-javascript">
function Car(model) {
  this.model = model;
}
const myCar = new Car("Honda"); 
console.log(myCar.model);
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/37aa2d94-bd25-45a0-8148-e3ca6641441c.png" alt="" />

<p>Arrow Function</p>
<pre><code class="language-javascript">
const Bike = (model) =&gt; {
  this.model = model;
};


const myBike = new Bike("Yamaha"); 
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/6200ccb6-81e5-408b-ae5e-178f13e61ff4.png" alt="" />

<h3>Cannot use <code>yield</code></h3>
<p>A generator function (<code>function*</code>) is a special type of function that can pause its execution, hand a value back to the caller using the <code>yield</code> keyword, and then resume later exactly where it left off. It acts like a state machine.</p>
<p>Example</p>
<pre><code class="language-javascript">function* snackMachine() {
  yield "Chips";
  yield "Chocolate";
  return "Empty";
}

const machine = snackMachine();
console.log(machine.next().value); // Output: "Chips"
console.log(machine.next().value); // Output: "Chocolate"
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/99810c88-fa49-449e-a3e0-c7a09bb1f3bc.png" alt="" />

<p>Arrow functions were strictly designed to be single-purpose, run-to-completion expressions. The designers of JavaScript (the TC39 committee) decided that combining the complex, state-pausing mechanics of generators with the ultra-concise syntax of arrow functions would make the language too confusing and harder to parse.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/68bd4f5d-e908-4a8f-82da-606dcc49e88c.png" alt="" />

<p>Now, when you are writing modern web apps, like subscribing to an observable stream of user data or handling a button click event in a component you just use an arrow function.</p>
<blockquote>
<p><em>"We cannot solve our problems with the same thinking we used when we created them."</em></p>
<p>— <strong>Albert Einstein</strong></p>
</blockquote>
<h3><strong>Let's Connect! 🚀</strong></h3>
<p>I’m currently deep-diving into the <strong>JavaScript</strong>, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!</p>
<ul>
<li><p><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/satpalsinhrana"><strong>Satpalsinh's Profile</strong></a></p>
</li>
<li><p><strong>Follow my Blog:</strong> <a href="http://blogs.satpal.cloud"><strong>blogs.satpal.cloud</strong></a></p>
</li>
</ul>
<p><strong>Keep coding and keep building.</strong></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Arrays Made Easy]]></title><description><![CDATA[Array
An array is a data structure used to store a collection of items. Think of it as a single variable that can hold multiple values under one name.
To know more on Array read my Article on Array : ]]></description><link>https://blogs.satpal.cloud/js-array-methods</link><guid isPermaLink="true">https://blogs.satpal.cloud/js-array-methods</guid><category><![CDATA[array methods]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Satpalsinh Rana]]></dc:creator><pubDate>Wed, 11 Mar 2026 16:59:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ff9b530c-5663-4afe-9563-11327987496d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Array</h2>
<p>An <strong>array</strong> is a data structure used to store a collection of items. Think of it as a single variable that can hold multiple values under one name.</p>
<p>To know more on Array read my Article on Array : <a href="https://blogs.satpal.cloud/js-array-1v1">JS Array 1v1</a></p>
<h2>Ways to Declare Array</h2>
<h3><strong>Array Literal (The Standard Way)</strong></h3>
<p>This is the most common and recommended way. It is concise and easy to read.</p>
<pre><code class="language-javascript">const GOT = ["Westoras", "Kings Landings" , 1 , false];
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ce7f2336-777c-41ea-99b6-409e151019d0.png" alt="" />

<h3><code>Array()</code> Constructor</h3>
<p>You can use the built-in <code>Array</code> global object. This behaves differently depending on how many arguments you pass.</p>
<pre><code class="language-javascript">// Case A: Multiple arguments (creates an array with these items)
const numbers = new Array(1, 2, 3); // [1, 2, 3]

// Case B: Single numerical argument 
const emptySlots = new Array(5); 
// Creates an array of length 5 with NO items
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/99b1df35-f7aa-4084-ac75-ca3873e3ca21.png" alt="" />

<h3><code>Array.of()</code></h3>
<p>Introduced in ES6, this was created to fix the Single Argument confusion of the <code>Array()</code> constructor.</p>
<pre><code class="language-javascript">const singleNum = Array.of(5); // [5]
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/1ccd82ea-d4a8-48d5-8a49-2c7792e75158.png" alt="" />

<h3><code>Array.from()</code></h3>
<p>This is used to create an array from an <strong>array-like</strong> or <strong>iterable</strong> object.</p>
<pre><code class="language-javascript">// From a string
const letters = Array.from("Hello"); // ["H", "e", "l", "l", "o"]

// Using a mapping function (2nd argument)
const squares = Array.from([1, 2, 3], x =&gt; x * x); // [1, 4, 9]
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/168d00ce-0cfe-44ee-b9ca-f1e107a431cc.png" alt="" />

<h3>Spread Operator (<code>...</code>)</h3>
<p>Often used to clone an existing array or convert other iterables.</p>
<pre><code class="language-javascript">const original = [1, 2, 3];
const clone = [...original];
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/63b7834d-4867-4a9b-bb9a-cfedcc961b31.png" alt="" />

<h1>Arrays Methods</h1>
<h2>Static Methods</h2>
<p>A static method is a function belonging to a class rather than an instance of that class.</p>
<h2><code>Array.isArray()</code></h2>
<p>Think of <code>Array.isArray()</code> as a specialized security guard at a club. His only job is to check if</p>
<h3>BTS of isArray</h3>
<ol>
<li><p><strong>The "Are you even an Object?" Check</strong><br />First, the guard checks if you are an object. If you are just a piece of text (string), a number, or a simple <code>true/false</code>, he doesn't even look at your ID.<br />He says <strong>False</strong> immediately.</p>
</li>
<li><p><strong>The "Hidden Stamp" Check</strong><br />If you <em>are</em> an object, he looks for a hidden "Array" stamp inside you. In JavaScript, arrays are "special" objects because they have a <code>.length</code> property that grows and shrinks automatically. Only objects with this specific internal "DNA" get the stamp.<br />If he sees the stamp, he says <strong>True</strong>.</p>
</li>
<li><p><strong>The "Mask" (Proxy) Check</strong><br />Sometimes, an array wears a mask (called a <strong>Proxy</strong>). The guard is smart if he sees a mask, he asks the person to take it off so he can check the face underneath. If the person behind the mask is an array, he's happy.<br />He checks the real person and says <strong>True</strong>.</p>
</li>
</ol>
<h3><strong>Why not just use</strong> <code>instanceof</code><strong>?</strong></h3>
<p>You might see people use <code>myList instanceof Array</code>. While that usually works, it has one major weakness:</p>
<p>Imagine two different countries (Iframes). Each country has its own "Array" rules.</p>
<ul>
<li><p><code>instanceof</code> is like a guard who only recognizes passports from his <em>own</em> country. If an array comes from another country (iframe), he says "I don't know you!"</p>
</li>
<li><p><code>Array.isArray()</code> is like a guard who knows what an Array looks like regardless of what country it came from. It's the universal gold standard.</p>
</li>
</ul>
<h3><code>of() &amp; from()</code></h3>
<p>As discussed above it is used to create an Array.</p>
<h3><code>fromAsync()</code></h3>
<p>New available method(2024), that creates an array from an <strong>async</strong> iterable, iterable, or array-like object and returns the result as a <strong>Promise</strong>.</p>
<pre><code class="language-javascript">const urls = [
  "https://jsonplaceholder.typicode.com/posts/1",
  "https://jsonplaceholder.typicode.com/posts/2",
  "https://jsonplaceholder.typicode.com/posts/3"
]

const responses = await Array.fromAsync(urls, async (url) =&gt; {
  const res = await fetch(url)
  return res.status
})

console.log(responses) // [200,200,200]
</code></pre>
<h2>Instance Methods</h2>
<h3>Mutator Methods</h3>
<p>These methods modify the array they are called on.</p>
<ul>
<li><p><code>push()</code> <strong>/</strong> <code>pop()</code>: Add to the end / Remove from the end. (Fast)</p>
</li>
<li><p><code>unshift()</code> <strong>/</strong> <code>shift()</code>: Add to the front / Remove from the front. (Slow, re-indexes everything).</p>
</li>
<li><p><code>splice()</code>: The surgical blade. Adds or removes elements at any index.</p>
</li>
<li><p><code>sort()</code>: Reorders elements. By default, it converts everything to strings to sort them, which is why <code>[10, 2]</code> becomes <code>[10, 2]</code> because "1" comes before "2".</p>
</li>
<li><p><code>reverse()</code>: Flips the array.</p>
</li>
<li><p><code>fill()</code>: Replaces a range of elements with a static value.</p>
</li>
<li><p><code>copyWithin()</code>: Copies a part of the array to another location <em>within the same array</em> without changing its length.</p>
</li>
</ul>
<h3>Accessors Methods</h3>
<p>These do <strong>not</strong> touch the original array. They return a new value or a new array.</p>
<ul>
<li><p><code>at()</code>: Takes an index and returns the item. It supports negative indices! <code>arr.at(-1)</code> gives you the last item.</p>
</li>
<li><p><code>concat()</code>: Merges two arrays into a new one.</p>
</li>
<li><p><code>join()</code>: Squashes the array into a string.</p>
</li>
<li><p><code>slice()</code>: Takes a "snapshot" of a portion of the array.</p>
</li>
<li><p><code>indexOf()</code> <strong>/</strong> <code>lastIndexOf()</code>: Returns the first or last index where a value is found.</p>
</li>
<li><p><code>includes()</code>: Returns <code>true/false</code> if a value exists.</p>
</li>
<li><p><code>toString()</code> <strong>/</strong> <code>toLocaleString()</code>: Converts the array to a string (local version handles dates/currency better).</p>
</li>
</ul>
<h3>The New Immutable Methods (ES2023)</h3>
<p>These are the modern versions.</p>
<ul>
<li><p><code>toReversed()</code>: Like <code>reverse()</code>, but leaves the original alone.</p>
</li>
<li><p><code>toSorted()</code>: Like <code>sort()</code>, but returns a new sorted array.</p>
</li>
<li><p><code>toSpliced()</code>: The safe version of <code>splice()</code>.</p>
</li>
<li><p><code>with()</code>: The safe way to change one item. <code>arr.with(2, "New")</code> returns a new array with the item at index 2 changed.</p>
</li>
</ul>
<h3>Iterators methods</h3>
<p>These methods use a callback function to process the array.</p>
<ul>
<li><p><code>forEach()</code>: Executes code for each item. Returns <code>undefined</code>.</p>
</li>
<li><p><code>map()</code> : Transforms each element of an array and returns a <strong>new array</strong>.</p>
</li>
<li><p><code>some()</code>: Checks if <strong>at least one</strong> item passes a test. Returns <strong>Boolean</strong>.</p>
</li>
<li><p><code>every()</code>: Checks if <strong>all</strong> items pass a test. Returns <strong>Boolean</strong>.</p>
</li>
<li><p><code>find()</code>: Finds the <strong>first</strong> item that matches. Returns <strong>The Item</strong> (or <code>undefined</code>).</p>
</li>
<li><p><code>findLast()</code>: Finds the <strong>last</strong> item that matches. Returns <strong>The Item</strong>.</p>
</li>
<li><p><code>findIndex()</code>: Finds the index of the <strong>first</strong> match. Returns <strong>Number</strong>.</p>
</li>
<li><p><code>findLastIndex()</code>: Finds the index of the <strong>last</strong> match. Returns <strong>Number</strong>.</p>
</li>
<li><p><code>reduce()</code>: Boils the array down to a <strong>Single Value</strong> (like a sum or a single object).</p>
</li>
<li><p><code>reduceRight()</code>: Same as reduce, but starts from the <strong>end</strong> of the array.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/ec9c237e-05c1-4cc9-8514-e56b15f7299c.png" alt="" style="display:block;margin:0 auto" />

<h3>Revise Most Common but tricky methods</h3>
<h3><code>sort()</code></h3>
<p>The most common mistake with <code>sort()</code> is assuming it sorts numbers correctly by default. In the JS Kingdoms, <code>sort()</code> treats everyone like a string, comparing them by their "dictionary" order rather than their value.</p>
<ul>
<li><p><strong>The Quirk:</strong> By default, <code>[10, 2, 22]</code> becomes <code>[10, 2, 22]</code> because "1" comes before "2" in Unicode.</p>
</li>
<li><p><strong>The Fix:</strong> You must provide a <strong>compare function</strong>.</p>
</li>
</ul>
<pre><code class="language-javascript">const powerLevels = [10, 2, 22, 5];

// Correct numeric sort
powerLevels.sort((a, b) =&gt; a - b); 
// Output: [2, 5, 10, 22]

// BTS Logic: If (a - b) is negative, 'a' comes first. 
// If positive, 'b' comes first. If 0, they stay put.
</code></pre>
<h3><code>reduce()</code></h3>
<p>This is arguably the most powerful yet confusing method. It takes an entire army of data and reduces it into a <strong>single value</strong>, which could be a number, a string, or even a completely different object.</p>
<ul>
<li><p><strong>The Strategy:</strong> It uses an <strong>accumulator</strong> (the running total) and the <strong>current value</strong>.</p>
</li>
<li><p><strong>The Pro Tip:</strong> Always provide an <strong>initial value</strong> to avoid errors with empty arrays.</p>
</li>
</ul>
<pre><code class="language-javascript">const treasury = [100, 200, 300];

const totalWealth = treasury.reduce((acc, gold) =&gt; {
  return acc + gold;
}, 0); // 0 is the starting point

console.log(totalWealth); // 600
</code></pre>
<h3><code>splice()</code></h3>
<p>Unlike <code>slice()</code>, which is a peaceful scout, <code>splice()</code> is a warrior that changes the original array. It is complex because it handles <strong>deleting</strong> and <strong>inserting</strong> at the same time.</p>
<p><strong>The Syntax:</strong> <code>splice(index, howManyToRemove, itemToInsert1, itemToInsert2...)</code></p>
<pre><code class="language-javascript">const houses = ["Stark", "Lannister", "Targaryen"];

// At index 1, remove 1 item and add "Tyrell" and "Martell"
houses.splice(1, 1, "Tyrell", "Martell");

console.log(houses); 
// ["Stark", "Tyrell", "Martell", "Targaryen"]
</code></pre>
<h3><code>flatMap()</code></h3>
<p>Often, you’ll find yourself using <code>.map()</code> followed by <code>.flat()</code>. <code>flatMap()</code> combines these into a single pass, which is more performant and cleaner to read.</p>
<ul>
<li><strong>The Strategy:</strong> It maps each element using a mapping function, then flattens the result by one level.</li>
</ul>
<pre><code class="language-javascript">const messages = ["Winter is", "Coming soon"];

const words = messages.flatMap(msg =&gt; msg.split(" "));
// Output: ["Winter", "is", "Coming", "soon"]

// Without flatMap, you'd get: [["Winter", "is"], ["Coming", "soon"]]
</code></pre>
<blockquote>
<p>"The best way to predict the future is to create it."<br />— <em>Peter Drucker</em></p>
</blockquote>
<h3><strong>Let's Connect! 🚀</strong></h3>
<p>I’m currently deep-diving into the <strong>JavaScript</strong>, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!</p>
<ul>
<li><p><strong>Connect on LinkedIn:</strong> <a href="https://www.linkedin.com/in/satpalsinhrana"><strong>Satpalsinh's Profile</strong></a></p>
</li>
<li><p><strong>Follow my Blog:</strong> <a href="http://blogs.satpal.cloud"><strong>blogs.satpal.cloud</strong></a></p>
</li>
</ul>
<p><strong>Keep coding and keep building.</strong></p>
]]></content:encoded></item></channel></rss>