<?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[Swarup-blog]]></title><description><![CDATA[Swarup-blog]]></description><link>https://blogs.swarupdas.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 24 Apr 2026 19:21:44 GMT</lastBuildDate><atom:link href="https://blogs.swarupdas.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Prototypal Inheritance in JavaScript]]></title><description><![CDATA[When I started learning JavaScript, one sentence kept popping up everywhere:

“JavaScript uses prototypal inheritance.”

At first, it sounded intimidating. But once I understood how property lookup actually works, everything became much clearer.
This...]]></description><link>https://blogs.swarupdas.dev/prototypal-inheritance-in-javascript</link><guid isPermaLink="true">https://blogs.swarupdas.dev/prototypal-inheritance-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[prototyping]]></category><category><![CDATA[prototypeal-inheritance]]></category><category><![CDATA[__proto__]]></category><category><![CDATA[prototype chain]]></category><category><![CDATA[prototype in javacsript]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Sat, 24 Jan 2026 14:29:54 GMT</pubDate><content:encoded><![CDATA[<hr />
<p>When I started learning JavaScript, one sentence kept popping up everywhere:</p>
<blockquote>
<p><strong>“JavaScript uses prototypal inheritance.”</strong></p>
</blockquote>
<p>At first, it sounded intimidating. But once I understood <em>how property lookup actually works</em>, everything became much clearer.</p>
<p>This blog explains <strong>prototypal inheritance from the ground up</strong>, using <strong>simple examples</strong>, and <strong>real intuition</strong>.</p>
<hr />
<h2 id="heading-what-is-prototypal-inheritance">🧠 What Is Prototypal Inheritance?</h2>
<p><strong>Prototypal inheritance</strong> in JavaScript is a mechanism where <strong>objects inherit properties and methods from other objects</strong>.</p>
<p>Unlike classical languages (Java, C++), JavaScript does <strong>not copy</strong> properties from parent to child.<br />Instead, it <strong>delegates property access</strong> through a chain of objects.</p>
<blockquote>
<p>This is why prototypal inheritance is better described as <strong>delegation</strong>, not traditional inheritance.</p>
</blockquote>
<hr />
<h2 id="heading-the-hidden-prototype">🔍 The Hidden <code>[[Prototype]]</code></h2>
<p>Every JavaScript object has a <strong>hidden internal property</strong> called:</p>
<pre><code class="lang-javascript">[[Prototype]]
</code></pre>
<p>This property points to <strong>another object</strong>, known as the object’s <strong>prototype</strong>.</p>
<p>You can access it using:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Object</span>.getPrototypeOf(obj);
<span class="hljs-comment">// or (not recommended for production)</span>
obj.__proto__;
</code></pre>
<hr />
<h2 id="heading-how-property-lookup-works-prototype-chain">🔗 How Property Lookup Works (Prototype Chain)</h2>
<p>When you try to access a property:</p>
<pre><code class="lang-js">obj.someProperty
</code></pre>
<p>JavaScript follows this process:</p>
<ol>
<li><p>Look for <code>someProperty</code> on <code>obj</code></p>
</li>
<li><p>❌ If not found → look at <code>obj.__proto__</code></p>
</li>
<li><p>❌ If still not found → look at <code>obj.__proto__.__proto__</code></p>
</li>
<li><p>Continue until:</p>
<ul>
<li><p>Property is found ✅</p>
</li>
<li><p>Or prototype becomes <code>null</code> ❌</p>
</li>
</ul>
</li>
</ol>
<p>This sequence is called the <strong>prototype chain</strong>.</p>
<hr />
<h2 id="heading-prototype-chain-diagram">📊 Prototype Chain Diagram</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769264919974/15ba466c-f523-463d-9280-5b1562311e1b.png" alt class="image--center mx-auto" /></p>
<p>Once JavaScript reaches <code>null</code>, the search stops.</p>
<hr />
<h2 id="heading-prototypal-inheritance-using-constructor-functions">🏗️ Prototypal Inheritance Using Constructor Functions</h2>
<p>Let’s look at a classic and very common example.</p>
<h3 id="heading-parent-constructor">Parent Constructor</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-comment">// Method added to prototype</span>
Animal.prototype.makeSound = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The <span class="hljs-subst">${<span class="hljs-built_in">this</span>.constructor.name}</span> makes a sound.`</span>);
};
</code></pre>
<hr />
<h3 id="heading-child-constructor">Child Constructor</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">name</span>) </span>{
  Animal.call(<span class="hljs-built_in">this</span>, name); <span class="hljs-comment">// Call parent constructor</span>
}
</code></pre>
<hr />
<h3 id="heading-setting-up-the-prototype-chain">Setting Up the Prototype Chain</h3>
<pre><code class="lang-js"><span class="hljs-built_in">Object</span>.setPrototypeOf(Dog.prototype, Animal.prototype);
</code></pre>
<p>Now <code>Dog</code> inherits from <code>Animal</code>.</p>
<hr />
<h3 id="heading-adding-child-specific-method">Adding Child-Specific Method</h3>
<pre><code class="lang-js">Dog.prototype.bark = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Woof!"</span>);
};
</code></pre>
<hr />
<h3 id="heading-creating-an-instance">Creating an Instance</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bolt = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Bolt"</span>);

<span class="hljs-built_in">console</span>.log(bolt.name);    <span class="hljs-comment">// Bolt</span>
bolt.makeSound();          <span class="hljs-comment">// The Dog makes a sound.</span>
bolt.bark();               <span class="hljs-comment">// Woof!</span>
</code></pre>
<hr />
<h2 id="heading-whats-happening-internally">🔍 What’s Happening Internally?</h2>
<p>When you call:</p>
<pre><code class="lang-js">bolt.makeSound();
</code></pre>
<p>JavaScript does this:</p>
<ol>
<li><p>Look for <code>makeSound</code> on <code>bolt</code></p>
</li>
<li><p>❌ Not found</p>
</li>
<li><p>Look on <code>Dog.prototype</code></p>
</li>
<li><p>❌ Not found</p>
</li>
<li><p>Look on <code>Animal.prototype</code></p>
</li>
<li><p>✅ Found → execute</p>
</li>
</ol>
<hr />
<h2 id="heading-prototype-chain-for-this-example">🔁 Prototype Chain for This Example</h2>
<pre><code class="lang-javascript">bolt
  ↓
Dog.prototype
  ↓
Animal.prototype
  ↓
<span class="hljs-built_in">Object</span>.prototype
  ↓
<span class="hljs-literal">null</span>
</code></pre>
<hr />
<h2 id="heading-important-notes-very-common-confusion">⚠️ Important Notes (Very Common Confusion)</h2>
<h3 id="heading-makesound-is-not-copied">✔ <code>.makeSound</code> is NOT copied</h3>
<p>The method exists <strong>only once</strong> on <code>Animal.prototype</code>.<br />All <code>Dog</code> instances <strong>share</strong> it.</p>
<p>This is <strong>memory efficient</strong>.</p>
<hr />
<h3 id="heading-delegation-not-classical-inheritance">✔ Delegation, Not Classical Inheritance</h3>
<p>JavaScript doesn’t duplicate methods like class-based languages.</p>
<p>Instead:</p>
<blockquote>
<p><strong>If an object doesn’t have a property, it delegates the lookup to its prototype.</strong></p>
</blockquote>
<hr />
<h3 id="heading-about-objectcreate-vs-objectsetprototypeof">❗ About <code>Object.create()</code> vs <code>Object.setPrototypeOf()</code></h3>
<ul>
<li><p><code>Object.create(proto)</code> is <strong>still valid and widely used</strong></p>
</li>
<li><p><code>Object.setPrototypeOf()</code> is <strong>more explicit</strong> but slower if overused</p>
</li>
</ul>
<p>Both work - just understand <strong>what they do</strong>.</p>
<hr />
<h2 id="heading-another-simple-example-person">🧑‍💻 Another Simple Example (Person)</h2>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

Person.prototype.sayHello = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>
  );
};

<span class="hljs-keyword">const</span> user1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Swarup"</span>, <span class="hljs-number">25</span>);
user1.sayHello();
</code></pre>
<p>Again:</p>
<ul>
<li><p><code>sayHello</code> is <strong>not on</strong> <code>user1</code></p>
</li>
<li><p>It lives on <code>Person.prototype</code></p>
</li>
</ul>
<hr />
<h2 id="heading-key-concepts-recap">🧩 Key Concepts Recap</h2>
<h3 id="heading-prototypes">🔹 Prototypes</h3>
<p>Every object has a prototype (another object).</p>
<h3 id="heading-proto">🔹 <code>__proto__</code></h3>
<p>Points to the object’s prototype (internal linkage).</p>
<h3 id="heading-prototype">🔹 <code>prototype</code></h3>
<p>A property on constructor functions used for inheritance.</p>
<pre><code class="lang-js">user1.__proto__ === Person.prototype; <span class="hljs-comment">// true</span>
</code></pre>
<p>This line clears <strong>a lot of confusion</strong>.</p>
<hr />
<h2 id="heading-what-about-es6-classes">🆕 What About ES6 Classes?</h2>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  greet() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
  }
}
</code></pre>
<p>Even here:</p>
<ul>
<li><p>Methods go to <code>Person.prototype</code></p>
</li>
<li><p>Inheritance still uses the <strong>prototype chain</strong></p>
</li>
</ul>
<p>👉 Classes are just <strong>syntax sugar</strong> over prototypes.</p>
<hr />
<h2 id="heading-final-takeaway">🧠 Final Takeaway</h2>
<blockquote>
<p><strong>JavaScript doesn’t copy properties—it looks them up through prototypes.</strong></p>
</blockquote>
<p>Once you understand this lookup process, topics like:</p>
<ul>
<li><p><code>this</code></p>
</li>
<li><p>classes</p>
</li>
<li><p>inheritance</p>
</li>
<li><p>built-in methods</p>
</li>
</ul>
<p>start making <strong>much more sense</strong>.</p>
<hr />
<h2 id="heading-closing-thought">✨ Closing Thought</h2>
<p>Prototypal inheritance feels confusing only when we try to force <strong>class-based thinking</strong> onto JavaScript.</p>
<p>When you think in terms of:</p>
<blockquote>
<p><em>“If it’s not here, JavaScript will check somewhere else”</em></p>
</blockquote>
<p>-everything clicks.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Power Trio: Mastering Call, Apply, and Bind]]></title><description><![CDATA[If you have been working with JavaScript for a while, you’ve likely bumped into the this keyword. It’s powerful, but it can be slippery. Sometimes this doesn’t refer to what you think it does.
This is where Call, Apply, and Bind come to the rescue. T...]]></description><link>https://blogs.swarupdas.dev/javascript-power-trio-mastering-call-apply-and-bind</link><guid isPermaLink="true">https://blogs.swarupdas.dev/javascript-power-trio-mastering-call-apply-and-bind</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[call]]></category><category><![CDATA[Bind]]></category><category><![CDATA[apply]]></category><category><![CDATA[this keyword]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Fri, 23 Jan 2026 15:35:34 GMT</pubDate><content:encoded><![CDATA[<p>If you have been working with JavaScript for a while, you’ve likely bumped into the <code>this</code> keyword. It’s powerful, but it can be slippery. Sometimes <code>this</code> doesn’t refer to what you think it does.</p>
<p>This is where <strong>Call</strong>, <strong>Apply</strong>, and <strong>Bind</strong> come to the rescue. These three methods allow you to explicitly determine what <code>this</code> refers to, giving you full control over the execution context of your functions.</p>
<p>Let's break them down.</p>
<h2 id="heading-the-setup-a-real-world-example">The Setup: A Real-World Example</h2>
<p>Imagine we have a <code>person</code> object with a first and last name. We also have a standalone function <code>greet</code> that is <em>not</em> attached to the object but uses <code>this</code> to access data.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person1 = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Doe"</span>
};

<span class="hljs-keyword">const</span> person2 = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Sarah"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Smith"</span>
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">greeting, punctuation</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${greeting}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.firstName}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lastName}</span><span class="hljs-subst">${punctuation}</span>`</span>);
}
</code></pre>
<p>If you try to run <code>greet("Hello", "!")</code> on its own, it will fail (or print undefined) because <code>this</code> doesn't point to <code>person1</code> or <code>person2</code>. It points to the global window object.</p>
<p>We need a way to tell the function: "Hey, run this code, but pretend <code>this</code> is <code>person1</code>."</p>
<h2 id="heading-1-call-the-direct-dial">1. Call: The Direct Dial</h2>
<p>The <code>call()</code> method invokes a function immediately and allows you to pass in arguments one by one.</p>
<p><strong>Syntax:</strong> <a target="_blank" href="http://function.call"><code>function.call</code></a><code>(thisArg, arg1, arg2, ...)</code></p>
<p>Let's use it to make our <code>greet</code> function work with <code>person1</code>:</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// The first argument is the object we want 'this' to refer to.</span>
<span class="hljs-comment">// The subsequent arguments are the parameters for the function.</span>
greet.call(person1, <span class="hljs-string">"Hello"</span>, <span class="hljs-string">"!"</span>); 

<span class="hljs-comment">// Output: Hello, John Doe!</span>
</code></pre>
<p>We can easily switch the context to <code>person2</code> just by changing the first argument:</p>
<p>JavaScript</p>
<pre><code class="lang-javascript">greet.call(person2, <span class="hljs-string">"Hi"</span>, <span class="hljs-string">"."</span>); 

<span class="hljs-comment">// Output: Hi, Sarah Smith.</span>
</code></pre>
<p><strong>Key Takeaway:</strong> Use <code>call</code> when you want to invoke a function immediately and pass arguments individually.</p>
<h2 id="heading-2-apply-the-array-approach">2. Apply: The Array Approach</h2>
<p>The <code>apply()</code> method is almost identical to <code>call()</code>. The only difference is how it handles function arguments. Instead of passing arguments one by one, you pass them as a single <strong>array</strong>.</p>
<p><strong>Syntax:</strong> <code>function.apply(thisArg, [argsArray])</code></p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> args = [<span class="hljs-string">"Good morning"</span>, <span class="hljs-string">"!!!"</span>];

<span class="hljs-comment">// We pass the arguments as an array</span>
greet.apply(person1, args); 

<span class="hljs-comment">// Output: Good morning, John Doe!!!</span>
</code></pre>
<p><strong>Key Takeaway:</strong> Use <code>apply</code> when your arguments are already in an array or list format. A handy mnemonic: <strong>A</strong>pply takes an <strong>A</strong>rray.</p>
<h2 id="heading-3-bind-the-permanent-connection">3. Bind: The Permanent Connection</h2>
<p>Both <code>call</code> and <code>apply</code> execute the function <em>immediately</em>. But what if you don't want to run the function right now? What if you want to create a version of the function that you can use later, but with <code>this</code> permanently set to a specific object?</p>
<p>That is what <code>bind()</code> does. It returns a <strong>new function</strong> instance.</p>
<p><strong>Syntax:</strong> <code>const newFunc = function.bind(thisArg, arg1, arg2, ...)</code></p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create a new function where 'this' is permanently bound to person2</span>
<span class="hljs-keyword">const</span> greetSarah = greet.bind(person2);

<span class="hljs-comment">// We can run this new function whenever we want</span>
greetSarah(<span class="hljs-string">"Greetings"</span>, <span class="hljs-string">"."</span>); 
<span class="hljs-comment">// Output: Greetings, Sarah Smith.</span>

<span class="hljs-comment">// Even if we try to override it, 'this' stays bound to person2</span>
greetSarah.call(person1, <span class="hljs-string">"Yo"</span>, <span class="hljs-string">"!"</span>); 
<span class="hljs-comment">// Output: Yo, Sarah Smith! (Still Sarah!)</span>
</code></pre>
<p><strong>Key Takeaway:</strong> Use <code>bind</code> when you want to set the <code>this</code> value now but execute the function later (commonly used in event listeners and React components).</p>
<h2 id="heading-summary">Summary</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Method</strong></td><td><strong>Execution</strong></td><td><strong>Arguments</strong></td><td><strong>Usage</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Call</strong></td><td>Immediate</td><td>Comma separated (arg1, arg2)</td><td>When you have individual arguments.</td></tr>
<tr>
<td><strong>Apply</strong></td><td>Immediate</td><td>Array ([arg1, arg2])</td><td>When arguments are in a list/array.</td></tr>
<tr>
<td><strong>Bind</strong></td><td>Later (Returns a function)</td><td>Comma separated</td><td>When you need a function to be called later with a specific context.</td></tr>
</tbody>
</table>
</div><p>Mastering these three methods gives you the ability to borrow methods from other objects and write cleaner, more reusable JavaScript code. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Mastering JavaScript's this Keyword: A Real-Life Guide]]></title><description><![CDATA[The definition seems simple: this refers to the current execution context.
But in practice, it feels like this has a mind of its own. It changes based on how you call a function, not just where you write it.
In this guide, we’ll break down every scen...]]></description><link>https://blogs.swarupdas.dev/mastering-javascripts-this-keyword-a-real-life-guide</link><guid isPermaLink="true">https://blogs.swarupdas.dev/mastering-javascripts-this-keyword-a-real-life-guide</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[this keyword]]></category><category><![CDATA[this keyword in javascript]]></category><category><![CDATA[this]]></category><category><![CDATA[this in js]]></category><category><![CDATA[This]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Thu, 22 Jan 2026 12:11:22 GMT</pubDate><content:encoded><![CDATA[<hr />
<p>The definition seems simple: <code>this</code> refers to the current execution context.</p>
<p>But in practice, it feels like <code>this</code> has a mind of its own. It changes based on <em>how</em> you call a function, not just <em>where</em> you write it.</p>
<p>In this guide, we’ll break down every scenario - from global scope to arrow functions - using a <strong>real-life analogy</strong> so you never have to guess again.</p>
<hr />
<h2 id="heading-the-analogy-the-smart-home-remote">The Analogy: The "Smart Home" Remote</h2>
<p>Imagine you have a <strong>Universal Remote Control</strong>.</p>
<p>This remote has a single button labeled <strong>"Turn On Lights"</strong>. The tricky part is that the remote doesn't have a specific room hardcoded into it. Instead, it decides which lights to turn on based on <strong>which room you are standing in</strong> when you press the button.</p>
<p>In this analogy:</p>
<ul>
<li><p>The <strong>Remote's Button</strong> is the <strong>Function</strong>.</p>
</li>
<li><p>The <strong>Room</strong> you are standing in is the <strong>Context (</strong><code>this</code>).</p>
</li>
</ul>
<p>Let's explore how this works in every JavaScript scenario.</p>
<hr />
<h2 id="heading-1-used-globally-standing-in-the-street">1. Used Globally (Standing in the Street)</h2>
<p>What happens if you use the remote while standing outside on the street, not inside any specific room?</p>
<p>In JavaScript, the "street" is the <strong>Global Scope</strong>.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); 
<span class="hljs-comment">// Output (Browser): Window object</span>
<span class="hljs-comment">// Output (Node.js): Global object</span>
</code></pre>
<p><strong>The Rule:</strong> In the global scope, <code>this</code> refers to the global object (the <code>window</code> in a browser).</p>
<hr />
<h2 id="heading-2-regular-function-call-the-free-invocation">2. Regular Function Call (The "Free" Invocation)</h2>
<p>This is where things get tricky. If you define a function and just call it plainly, it’s like pressing the remote button while standing in the middle of a hallway.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showThis</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}

showThis(); 
<span class="hljs-comment">// Non-strict mode: Window (Global Object)</span>
<span class="hljs-comment">// Strict mode ('use strict'): undefined</span>
</code></pre>
<p><strong>The Rule:</strong></p>
<ul>
<li><p><strong>Non-Strict Mode:</strong> JavaScript assumes you mean the Global Object (Window).</p>
</li>
<li><p><strong>Strict Mode:</strong> JavaScript protects you. Since you didn't specify an object, <code>this</code> is <code>undefined</code>.</p>
</li>
</ul>
<hr />
<h2 id="heading-3-method-call-implicit-binding">3. Method Call (Implicit Binding)</h2>
<p>This is the most common and intuitive scenario. You are "inside" an object, and you use a function belonging to that object.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> livingRoom = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Living Room'</span>,
  <span class="hljs-attr">showThis</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  },
};

livingRoom.showThis(); 
<span class="hljs-comment">// Output: "Living Room"</span>
</code></pre>
<p><strong>The Rule:</strong> Look at the call site. If there is a <strong>dot</strong> to the left of the function (<code>livingRoom.showThis()</code>), the object on the left is <code>this</code>.</p>
<hr />
<h2 id="heading-4-the-trap-losing-context">4. The Trap: Losing Context</h2>
<p>This is the #1 bug developers encounter. What happens if you take the functionality <em>out</em> of the object and save it to a variable?</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> livingRoom = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Living Room'</span>,
  <span class="hljs-attr">showThis</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  },
};

<span class="hljs-comment">// We are assigning the definition to a new variable</span>
<span class="hljs-keyword">const</span> showThisStandalone = livingRoom.showThis;

<span class="hljs-comment">// Now we call it without the object!</span>
showThisStandalone(); 
<span class="hljs-comment">// Output (Non-strict): Window</span>
<span class="hljs-comment">// Output (Strict): undefined</span>
</code></pre>
<p><strong>Real-Life Analogy:</strong> You took the "Turn On Lights" button <em>off</em> the Living Room remote and walked out into the street with just the button. It no longer knows it belongs to the Living Room.</p>
<p><strong>The Rule:</strong> If you call a function without the dot notation (even if it came from an object originally), it reverts to the <strong>Regular Function Call</strong> rules (Global or undefined).</p>
<hr />
<h2 id="heading-5-explicit-binding-call-apply-bind">5. Explicit Binding (<code>call</code>, <code>apply</code>, <code>bind</code>)</h2>
<p>Sometimes you want to borrow a remote from one room but use it in another. JavaScript gives us three tools to manually force <code>this</code> to be whatever we want.</p>
<ul>
<li><p><code>call()</code> / <code>apply()</code>: "Run this function NOW, but pretend I am <code>this</code> object."</p>
</li>
<li><p><code>bind()</code>: "Create a COPY of this function where <code>this</code> is permanently locked to this object."</p>
</li>
</ul>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> kitchen = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Kitchen'</span> };
<span class="hljs-keyword">const</span> bedroom = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Bedroom'</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">turnOnLights</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Lights on in the <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
}

<span class="hljs-comment">// Explicitly telling the function to use 'kitchen' as 'this'</span>
turnOnLights.call(kitchen); <span class="hljs-comment">// Output: Lights on in the Kitchen</span>
turnOnLights.call(bedroom); <span class="hljs-comment">// Output: Lights on in the Bedroom</span>
</code></pre>
<p><strong>The Rule:</strong> If you see <code>call</code>, <code>apply</code>, or <code>bind</code>, <code>this</code> is explicitly the object passed inside the parentheses.</p>
<hr />
<h2 id="heading-6-the-new-keyword-constructor-calls">6. The <code>new</code> Keyword (Constructor Calls)</h2>
<p>When you use the <code>new</code> keyword, you are acting like a construction worker building a brand-new house.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SmartRoom</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-comment">// 'this' = the new object being created right now</span>
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.showContext = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  }
}

<span class="hljs-keyword">const</span> myOffice = <span class="hljs-keyword">new</span> SmartRoom(<span class="hljs-string">'Office'</span>);
myOffice.showContext(); 
<span class="hljs-comment">// Output: SmartRoom { name: 'Office', showContext: [Function] }</span>
</code></pre>
<p><strong>The Rule:</strong> When <code>new</code> is used, JavaScript creates a fresh, empty object. <code>this</code> points to that new object.</p>
<hr />
<h2 id="heading-7-arrow-functions-the-exception">7. Arrow Functions (The Exception)</h2>
<p>ES6 introduced Arrow Functions (<code>=&gt;</code>), and they break all the previous rules.</p>
<p>Arrow functions <strong>do not</strong> have their own <code>this</code>. Instead, they inherit <code>this</code> from the code directly surrounding them (lexical scoping).</p>
<p>Think of an arrow function as a remote that is <strong>super-glued</strong> to the wall where it was created. You cannot change where it points, even with <code>.call()</code>.</p>
<p>JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> garage = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Garage'</span>,
  <span class="hljs-attr">openDoor</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Regular function: 'this' is the garage</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome to <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); 

    <span class="hljs-comment">// Arrow function: inherits 'this' from openDoor's scope</span>
    <span class="hljs-keyword">const</span> cleanup = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Cleaning <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
    };

    cleanup();
  }
};

garage.openDoor();
<span class="hljs-comment">// Output: Welcome to Garage</span>
<span class="hljs-comment">// Output: Cleaning Garage</span>
</code></pre>
<p><strong>The Rule:</strong> If it's an arrow function, look at where it was <em>defined</em>. It adopts the <code>this</code> from its parent scope.</p>
<hr />
<h2 id="heading-summary-the-who-wins-hierarchy">Summary: The "Who Wins?" Hierarchy</h2>
<p>If multiple rules seem to apply, follow this order of precedence (highest wins):</p>
<ol>
<li><p><strong>Arrow Function:</strong> Ignores everything, uses parent scope.</p>
</li>
<li><p><code>new</code> Keyword: <code>this</code> is the new instance.</p>
</li>
<li><p><code>call</code> / <code>apply</code> / <code>bind</code>: <code>this</code> is the specified object.</p>
</li>
<li><p><strong>Method Call (</strong><code>obj.method()</code>): <code>this</code> is the object before the dot.</p>
</li>
<li><p><strong>Free Invocation:</strong> <code>this</code> is Global (or <code>undefined</code> in strict mode).</p>
</li>
</ol>
<p>Mastering <code>this</code> takes practice, but once you understand that it's all about <strong>context</strong>, you'll be debugging like a pro in no time.</p>
<p><em>Did this clear up the confusion? Let me know in the comments!</em></p>
]]></content:encoded></item><item><title><![CDATA[Debounce vs Throttle in JavaScript]]></title><description><![CDATA[When building modern web applications, performance matters.Events like scroll, resize, keypress, or API calls can fire hundreds of times per second, leading to laggy UI and unnecessary network requests.
Two powerful techniques to handle this are Debo...]]></description><link>https://blogs.swarupdas.dev/debounce-vs-throttle-in-javascript</link><guid isPermaLink="true">https://blogs.swarupdas.dev/debounce-vs-throttle-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[debouncing]]></category><category><![CDATA[throttling]]></category><category><![CDATA[Debouncing and Throttling]]></category><category><![CDATA[Performance Optimization]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Sat, 10 Jan 2026 16:18:24 GMT</pubDate><content:encoded><![CDATA[<p>When building modern web applications, performance matters.<br />Events like <strong>scroll</strong>, <strong>resize</strong>, <strong>keypress</strong>, or <strong>API calls</strong> can fire <strong>hundreds of times per second</strong>, leading to laggy UI and unnecessary network requests.</p>
<p>Two powerful techniques to handle this are <strong>Debouncing</strong> and <strong>Throttling</strong>.</p>
<p>Let’s understand them <strong>intuitively</strong>, with <strong>diagrams, examples, and real-world use cases</strong>.</p>
<hr />
<h2 id="heading-why-do-we-need-debounce-amp-throttle">🔥 Why Do We Need Debounce &amp; Throttle?</h2>
<p>Imagine this code:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"resize"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Resizing..."</span>);
});
</code></pre>
<p>If the user resizes the browser continuously, this function will be executed <strong>again and again</strong> — sometimes hundreds of times per second 😵‍💫.</p>
<p>This can:</p>
<ul>
<li><p>Hurt performance</p>
</li>
<li><p>Flood APIs</p>
</li>
<li><p>Freeze the UI</p>
</li>
</ul>
<p>👉 <strong>Debounce</strong> and <strong>Throttle</strong> help control how often a function executes.</p>
<hr />
<h2 id="heading-what-is-debouncing">🕰️ What is Debouncing?</h2>
<p><strong>Debouncing</strong> ensures that a function is executed <strong>only after a certain amount of time has passed since the last event</strong>.</p>
<blockquote>
<p>“Wait until the user stops doing something.”</p>
</blockquote>
<h3 id="heading-real-world-analogy">🧠 Real-World Analogy</h3>
<p>Think of typing a message:</p>
<ul>
<li><p>You type continuously</p>
</li>
<li><p>The action happens <strong>only after you stop typing</strong></p>
</li>
</ul>
<hr />
<h3 id="heading-debounce-timeline">📊 Debounce Timeline</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768061638092/0067e59c-4ac2-477a-ac35-fca101988fb3.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-plaintext">Key Presses:  | | | | |      |
Time (ms):    0 50 100 150 300
Debounce(300ms)
Output:                   ✅ Function runs once
</code></pre>
<hr />
<h3 id="heading-common-use-cases">💡 Common Use Cases</h3>
<ul>
<li><p>Search input (API calls)</p>
</li>
<li><p>Form validation</p>
</li>
<li><p>Auto-save</p>
</li>
<li><p>Resize events</p>
</li>
</ul>
<hr />
<h3 id="heading-debounce-implementation-javascript">🧩 Debounce Implementation (JavaScript)</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">debounce</span>(<span class="hljs-params">fn, delay</span>) </span>{
  <span class="hljs-keyword">let</span> timer;

  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">clearTimeout</span>(timer);

    timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      fn.apply(<span class="hljs-built_in">this</span>, args);
    }, delay);
  };
}
</code></pre>
<hr />
<h3 id="heading-example-search-input">🧪 Example: Search Input</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">searchAPI</span>(<span class="hljs-params">query</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Searching for:"</span>, query);
}

<span class="hljs-keyword">const</span> debouncedSearch = debounce(searchAPI, <span class="hljs-number">500</span>);

input.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  debouncedSearch(e.target.value);
});
</code></pre>
<p>👉 API call happens <strong>only after the user stops typing for 500ms</strong></p>
<hr />
<h2 id="heading-what-is-throttling">⚡ What is Throttling?</h2>
<p><strong>Throttling</strong> ensures that a function is executed <strong>at most once in a given time interval</strong>, no matter how many times the event occurs.</p>
<blockquote>
<p>“Do it, but not too often.”</p>
</blockquote>
<hr />
<h3 id="heading-real-world-analogy-1">🧠 Real-World Analogy</h3>
<p>Imagine a lift that can move <strong>once every 5 seconds</strong>, even if people keep pressing the button.</p>
<hr />
<h3 id="heading-throttle-timeline">📊 Throttle Timeline</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768061494837/97d19c7d-8972-432a-90c6-9a9098563d08.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-plaintext">Scroll Events: | | | | | | | |
Throttle(300ms)
Output:        ✅     ✅     ✅
</code></pre>
<hr />
<h3 id="heading-common-use-cases-1">💡 Common Use Cases</h3>
<ul>
<li><p>Scroll handling</p>
</li>
<li><p>Button spam prevention</p>
</li>
<li><p>Window resize</p>
</li>
<li><p>Mouse movement tracking</p>
</li>
<li><p>Game mechanics</p>
</li>
</ul>
<hr />
<h3 id="heading-throttle-implementation-javascript">🧩 Throttle Implementation (JavaScript)</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">fn, limit</span>) </span>{
  <span class="hljs-keyword">let</span> lastCall = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">const</span> now = <span class="hljs-built_in">Date</span>.now();

    <span class="hljs-keyword">if</span> (now - lastCall &gt;= limit) {
      lastCall = now;
      fn.apply(<span class="hljs-built_in">this</span>, args);
    }
  };
}
</code></pre>
<hr />
<h3 id="heading-example-scroll-event">🧪 Example: Scroll Event</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleScroll</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Scrolling..."</span>);
}

<span class="hljs-keyword">const</span> throttledScroll = throttle(handleScroll, <span class="hljs-number">300</span>);

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"scroll"</span>, throttledScroll);
</code></pre>
<p>👉 Executes <strong>once every 300ms</strong>, no matter how fast you scroll</p>
<hr />
<h2 id="heading-debounce-vs-throttle-quick-comparison">🆚 Debounce vs Throttle (Quick Comparison)</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Debounce</td><td>Throttle</td></tr>
</thead>
<tbody>
<tr>
<td>Execution</td><td>After inactivity</td><td>At fixed intervals</td></tr>
<tr>
<td>Best for</td><td>Search, input, resize</td><td>Scroll, mouse move</td></tr>
<tr>
<td>API calls</td><td>✅ Yes</td><td>❌ Usually no</td></tr>
<tr>
<td>UI responsiveness</td><td>Waits</td><td>Immediate but controlled</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-when-to-use-what">🎯 When to Use What?</h2>
<h3 id="heading-use-debounce-when">✅ Use <strong>Debounce</strong> when:</h3>
<ul>
<li><p>You want the <strong>final result</strong></p>
</li>
<li><p>User input matters more than intermediate events</p>
</li>
<li><p>Example: Search bar, form validation</p>
</li>
</ul>
<h3 id="heading-use-throttle-when">✅ Use <strong>Throttle</strong> when:</h3>
<ul>
<li><p>You want <strong>continuous updates</strong></p>
</li>
<li><p>Need performance + responsiveness</p>
</li>
<li><p>Example: Infinite scroll, window resize</p>
</li>
</ul>
<hr />
<h2 id="heading-bonus-tip">🧠 Bonus Tip</h2>
<blockquote>
<p><strong>Debounce = “Wait”</strong><br /><strong>Throttle = “Limit”</strong></p>
</blockquote>
<p>If you remember just this line, you’ll never confuse them again 😉</p>
<hr />
<h2 id="heading-final-thoughts">🚀 Final Thoughts</h2>
<p>Debouncing and throttling are <strong>essential performance optimization techniques</strong> every frontend developer should master.</p>
<p>They help you:</p>
<ul>
<li><p>Build faster apps</p>
</li>
<li><p>Reduce unnecessary work</p>
</li>
<li><p>Improve user experience</p>
</li>
</ul>
<p>If you’re working with <strong>React, Vue, or Vanilla JS</strong>, these concepts apply everywhere.</p>
<hr />
<h3 id="heading-did-this-help">💬 Did this help?</h3>
<p>Drop a ❤️ or comment on Hashnode if this cleared your confusion.<br />Happy coding! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Gen-AI]]></title><description><![CDATA[Introduction to Generative AI: Understanding the Technology Reshaping Our World
Artificial Intelligence has entered a revolutionary phase with the emergence of Generative AI. From writing code to creating art, composing music to generating human-like...]]></description><link>https://blogs.swarupdas.dev/introduction-to-gen-ai</link><guid isPermaLink="true">https://blogs.swarupdas.dev/introduction-to-gen-ai</guid><category><![CDATA[genai]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Thu, 08 Jan 2026 18:30:00 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-introduction-to-generative-ai-understanding-the-technology-reshaping-our-world">Introduction to Generative AI: Understanding the Technology Reshaping Our World</h1>
<p>Artificial Intelligence has entered a revolutionary phase with the emergence of Generative AI. From writing code to creating art, composing music to generating human-like conversations, Generative AI is transforming how we interact with technology. Let's dive deep into this fascinating world.</p>
<h2 id="heading-what-is-generative-ai">What is Generative AI?</h2>
<p>Generative AI refers to artificial intelligence systems that can create new content—text, images, code, music, videos, and more—based on patterns learned from existing data. Unlike traditional AI that simply analyzes and classifies information, generative AI <strong>produces</strong> original content.</p>
<p>Think of it this way: if you show a traditional AI system thousands of cat photos, it learns to identify cats. But if you show a generative AI those same photos, it can create entirely new, realistic cat images that never existed before.</p>
<h3 id="heading-key-characteristics-of-generative-ai">Key Characteristics of Generative AI:</h3>
<ul>
<li><p><strong>Content Creation</strong>: Generates novel outputs including text, images, audio, and video</p>
</li>
<li><p><strong>Pattern Learning</strong>: Learns from massive datasets to understand patterns and relationships</p>
</li>
<li><p><strong>Contextual Understanding</strong>: Comprehends context to produce relevant and coherent outputs</p>
</li>
<li><p><strong>Versatility</strong>: Can perform multiple tasks across different domains</p>
</li>
</ul>
<h3 id="heading-how-does-it-work">How Does It Work?</h3>
<pre><code class="lang-plaintext">Training Data → Neural Networks → Pattern Recognition → Content Generation
</code></pre>
<p>Generative AI models are trained on vast amounts of data. During training, they learn:</p>
<ul>
<li><p>Statistical patterns in the data</p>
</li>
<li><p>Relationships between concepts</p>
</li>
<li><p>Contextual associations</p>
</li>
<li><p>Structural rules and conventions</p>
</li>
</ul>
<h2 id="heading-introduction-to-large-language-models-llms">Introduction to Large Language Models (LLMs)</h2>
<p>Large Language Models are a specific type of generative AI focused on understanding and generating human language. They're called "large" because they contain billions (sometimes trillions) of parameters—the adjustable weights that determine how the model processes information.</p>
<h3 id="heading-what-makes-llms-special">What Makes LLMs Special?</h3>
<p><strong>Scale</strong>: Models like GPT-4, Claude, and Gemini are trained on diverse internet text, books, articles, and code repositories, giving them broad knowledge.</p>
<p><strong>Emergent Abilities</strong>: As LLMs grow larger, they develop unexpected capabilities like reasoning, math problem-solving, and even coding—abilities not explicitly programmed.</p>
<p><strong>Transfer Learning</strong>: LLMs can apply knowledge from one domain to another, making them incredibly versatile.</p>
<h3 id="heading-popular-llm-families">Popular LLM Families:</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model Family</td><td>Developer</td><td>Key Strength</td></tr>
</thead>
<tbody>
<tr>
<td>GPT Series</td><td>OpenAI</td><td>Creative writing, conversational AI</td></tr>
<tr>
<td>Claude</td><td>Anthropic</td><td>Long conversations, detailed analysis</td></tr>
<tr>
<td>Gemini</td><td>Google</td><td>Multimodal capabilities</td></tr>
<tr>
<td>LLaMA</td><td>Meta</td><td>Open-source flexibility</td></tr>
<tr>
<td>Mistral</td><td>Mistral AI</td><td>Efficiency and performance</td></tr>
</tbody>
</table>
</div><h3 id="heading-how-llms-generate-text">How LLMs Generate Text:</h3>
<p>LLMs work by predicting the most likely next word (or token) based on the previous context. It's like an incredibly sophisticated autocomplete:</p>
<pre><code class="lang-plaintext">Input: "The future of AI is"
LLM Process: Analyze context → Calculate probabilities → Select next token
Output: "promising, with advancements in..."
</code></pre>
<h2 id="heading-ai-models-and-their-capabilities">AI Models and Their Capabilities</h2>
<p>Different AI models excel at different tasks. Let's explore the landscape:</p>
<h3 id="heading-1-text-generation-models">1. <strong>Text Generation Models</strong></h3>
<p><strong>Capabilities:</strong></p>
<ul>
<li><p>Writing articles, stories, and poetry</p>
</li>
<li><p>Code generation and debugging</p>
</li>
<li><p>Translation between languages</p>
</li>
<li><p>Summarization of long documents</p>
</li>
<li><p>Question answering and explanations</p>
</li>
</ul>
<p><strong>Examples:</strong> GPT-4, Claude, PaLM 2</p>
<h3 id="heading-2-image-generation-models">2. <strong>Image Generation Models</strong></h3>
<p><strong>Capabilities:</strong></p>
<ul>
<li><p>Creating original artwork from text descriptions</p>
</li>
<li><p>Photo editing and enhancement</p>
</li>
<li><p>Style transfer and image-to-image translation</p>
</li>
<li><p>Logo and design creation</p>
</li>
</ul>
<p><strong>Examples:</strong> DALL-E 3, Midjourney, Stable Diffusion</p>
<h3 id="heading-3-multimodal-models">3. <strong>Multimodal Models</strong></h3>
<p><strong>Capabilities:</strong></p>
<ul>
<li><p>Understanding both text and images</p>
</li>
<li><p>Answering questions about uploaded photos</p>
</li>
<li><p>Generating images from text descriptions</p>
</li>
<li><p>Video analysis and generation</p>
</li>
</ul>
<p><strong>Examples:</strong> GPT-4V, Gemini, Claude (with vision)</p>
<h3 id="heading-4-code-generation-models">4. <strong>Code Generation Models</strong></h3>
<p><strong>Capabilities:</strong></p>
<ul>
<li><p>Writing code in multiple programming languages</p>
</li>
<li><p>Debugging and code review</p>
</li>
<li><p>Explaining complex code</p>
</li>
<li><p>Converting between programming languages</p>
</li>
</ul>
<p><strong>Examples:</strong> GitHub Copilot, CodeLlama, GPT-4</p>
<h3 id="heading-model-size-vs-performance">Model Size vs Performance:</h3>
<pre><code class="lang-plaintext">Small Models (7B-13B parameters)
├─ Fast responses
├─ Lower computational cost
└─ Good for specific tasks

Medium Models (30B-70B parameters)
├─ Balanced performance
├─ Moderate resource needs
└─ Versatile applications

Large Models (100B+ parameters)
├─ Highest accuracy
├─ Complex reasoning
└─ Resource intensive
</code></pre>
<h2 id="heading-understanding-tokens-context-and-context-windows">Understanding Tokens, Context, and Context Windows</h2>
<p>These concepts are fundamental to how LLMs work. Let's break them down:</p>
<h3 id="heading-tokens-the-building-blocks">Tokens: The Building Blocks</h3>
<p>A <strong>token</strong> is the smallest unit of text that an LLM processes. Tokens can be:</p>
<ul>
<li><p>Whole words: "hello"</p>
</li>
<li><p>Parts of words: "un-" "break" "-able"</p>
</li>
<li><p>Punctuation: "." "!" "?"</p>
</li>
<li><p>Spaces and special characters</p>
</li>
</ul>
<p><strong>Example Tokenization:</strong></p>
<pre><code class="lang-plaintext">Text: "I love AI!"
Tokens: ["I", " love", " AI", "!"]
Token Count: 4 tokens
</code></pre>
<p><strong>General Rule of Thumb:</strong></p>
<ul>
<li><p>1 token ≈ 4 characters in English</p>
</li>
<li><p>1 token ≈ ¾ of a word on average</p>
</li>
<li><p>100 tokens ≈ 75 words</p>
</li>
</ul>
<h3 id="heading-context-what-the-model-remembers">Context: What the Model Remembers</h3>
<p><strong>Context</strong> refers to all the information the model considers when generating a response. This includes:</p>
<ul>
<li><p>Your current prompt or question</p>
</li>
<li><p>Previous messages in the conversation</p>
</li>
<li><p>System instructions</p>
</li>
<li><p>Any uploaded documents or images</p>
</li>
</ul>
<p>The model uses context to:</p>
<ul>
<li><p>Maintain conversation coherence</p>
</li>
<li><p>Reference earlier information</p>
</li>
<li><p>Understand relationships between ideas</p>
</li>
<li><p>Generate relevant responses</p>
</li>
</ul>
<h3 id="heading-context-window-the-memory-limit">Context Window: The Memory Limit</h3>
<p>The <strong>context window</strong> is the maximum number of tokens a model can process at once. Think of it as the model's working memory.</p>
<p><strong>Visualization:</strong></p>
<pre><code class="lang-plaintext">[Your Question] + [Conversation History] + [System Instructions] = Total Tokens

If Total Tokens &gt; Context Window → Oldest messages are forgotten
</code></pre>
<p><strong>Common Context Window Sizes:</strong></p>
<ul>
<li><p><strong>GPT-3.5</strong>: 16,000 tokens (~12,000 words)</p>
</li>
<li><p><strong>GPT-4</strong>: 128,000 tokens (~96,000 words)</p>
</li>
<li><p><strong>Claude 3.5 Sonnet</strong>: 200,000 tokens (~150,000 words)</p>
</li>
<li><p><strong>Gemini 1.5 Pro</strong>: 2,000,000 tokens (~1.5 million words)</p>
</li>
</ul>
<p><strong>Why Context Windows Matter:</strong></p>
<p>✅ <strong>Larger windows allow:</strong></p>
<ul>
<li><p>Longer conversations without losing history</p>
</li>
<li><p>Processing entire books or codebases</p>
</li>
<li><p>More detailed and comprehensive responses</p>
</li>
<li><p>Better understanding of complex topics</p>
</li>
</ul>
<p>❌ <strong>Limitations:</strong></p>
<ul>
<li><p>Processing more tokens costs more</p>
</li>
<li><p>Longer response times</p>
</li>
<li><p>Increased computational requirements</p>
</li>
</ul>
<h2 id="heading-interfaces-how-we-interact-with-generative-ai">Interfaces: How We Interact with Generative AI</h2>
<p>Generative AI is accessible through various interfaces, each suited for different use cases:</p>
<h3 id="heading-1-chat-interfaces">1. <strong>Chat Interfaces</strong></h3>
<p>The most popular way to interact with LLMs:</p>
<ul>
<li><p><strong>Web-based</strong>: ChatGPT, <a target="_blank" href="http://Claude.ai">Claude.ai</a>, Gemini</p>
</li>
<li><p><strong>Features</strong>: Conversation history, file uploads, voice input</p>
</li>
<li><p><strong>Best for</strong>: General use, learning, creative tasks</p>
</li>
</ul>
<h3 id="heading-2-api-application-programming-interface">2. <strong>API (Application Programming Interface)</strong></h3>
<p>For developers building AI-powered applications:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Example API call</span>
response = openai.ChatCompletion.create(
    model=<span class="hljs-string">"gpt-4"</span>,
    messages=[{<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Explain quantum computing"</span>}]
)
</code></pre>
<ul>
<li><strong>Best for</strong>: Integrating AI into apps, automation, scaling</li>
</ul>
<h3 id="heading-3-integrated-tools">3. <strong>Integrated Tools</strong></h3>
<p>AI embedded in existing software:</p>
<ul>
<li><p><strong>GitHub Copilot</strong>: Code suggestions in your IDE</p>
</li>
<li><p><strong>Notion AI</strong>: Writing assistance in notes</p>
</li>
<li><p><strong>Adobe Firefly</strong>: Image generation in Photoshop</p>
</li>
<li><p><strong>Best for</strong>: Workflow enhancement, productivity</p>
</li>
</ul>
<h3 id="heading-4-playground-environments">4. <strong>Playground Environments</strong></h3>
<p>Experimental interfaces with advanced controls:</p>
<ul>
<li><p>Temperature settings (creativity control)</p>
</li>
<li><p>Token limits</p>
</li>
<li><p>System prompts</p>
</li>
<li><p><strong>Best for</strong>: Testing, fine-tuning, advanced users</p>
</li>
</ul>
<h3 id="heading-5-command-line-interfaces">5. <strong>Command Line Interfaces</strong></h3>
<p>For technical users and automation:</p>
<pre><code class="lang-bash">claude-code <span class="hljs-string">"Create a REST API for a todo app"</span>
</code></pre>
<ul>
<li><strong>Best for</strong>: Development workflows, scripting, automation</li>
</ul>
<h2 id="heading-the-future-of-generative-ai">The Future of Generative AI</h2>
<p>Generative AI is evolving rapidly. Here's what's on the horizon:</p>
<p>🔮 <strong>Multimodal Integration</strong>: Models that seamlessly understand and generate text, images, audio, and video</p>
<p>🔮 <strong>Improved Reasoning</strong>: Better logical thinking and problem-solving capabilities</p>
<p>🔮 <strong>Personalization</strong>: AI that adapts to individual users' preferences and communication styles</p>
<p>🔮 <strong>Reduced Hallucinations</strong>: More accurate and reliable outputs</p>
<p>🔮 <strong>Efficiency</strong>: Smaller models with capabilities matching today's largest ones</p>
<h2 id="heading-getting-started-with-generative-ai">Getting Started with Generative AI</h2>
<p>Ready to explore? Here are some starting points:</p>
<ol>
<li><p><strong>Experiment with chat interfaces</strong> (free tiers available)</p>
</li>
<li><p><strong>Try different prompting techniques</strong> (be specific, provide context)</p>
</li>
<li><p><strong>Explore various models</strong> to find what works best for your needs</p>
</li>
<li><p><strong>Learn prompt engineering</strong> to get better results</p>
</li>
<li><p><strong>Stay updated</strong> on new developments and capabilities</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Generative AI and Large Language Models represent a paradigm shift in how we interact with computers. Understanding concepts like tokens, context windows, and model capabilities empowers you to use these tools effectively.</p>
<p>Whether you're a developer, creative professional, student, or just curious, there's never been a better time to explore the possibilities of Generative AI. The technology is here, accessible, and ready to augment human creativity and productivity in ways we're only beginning to understand.</p>
<hr />
<p><strong>Tags</strong>: #GenerativeAI #LLM #ArtificialIntelligence #MachineLearning #Technology #AI</p>
]]></content:encoded></item><item><title><![CDATA[Polyfills - Bridging Gaps in JavaScript]]></title><description><![CDATA[Imagine building a beautiful modern web application, only to discover it breaks in older browsers because they don't support the latest JavaScript features. This is where polyfills come to the rescue. Let's explore how these clever pieces of code hel...]]></description><link>https://blogs.swarupdas.dev/polyfills-bridging-gaps-in-javascript</link><guid isPermaLink="true">https://blogs.swarupdas.dev/polyfills-bridging-gaps-in-javascript</guid><category><![CDATA[array polyfills]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[polyfills]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Sun, 28 Dec 2025 18:04:18 GMT</pubDate><content:encoded><![CDATA[<p>Imagine building a beautiful modern web application, only to discover it breaks in older browsers because they don't support the latest JavaScript features. This is where polyfills come to the rescue. Let's explore how these clever pieces of code help bridge the gap between modern JavaScript and older environments.</p>
<h2 id="heading-what-is-a-polyfill-and-why-is-it-important">What is a Polyfill and Why is it Important?</h2>
<h3 id="heading-understanding-polyfills">Understanding Polyfills</h3>
<p>A <strong>polyfill</strong> is a piece of code (usually JavaScript) that provides modern functionality on older browsers that don't natively support it. The term was coined by Remy Sharp and comes from the idea of "filling in the gaps" in browser support—like polyfilla (a UK brand of wall filler) fills cracks in walls.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Modern code you want to write</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> hasThree = numbers.includes(<span class="hljs-number">3</span>); <span class="hljs-comment">// ES2016 feature</span>

<span class="hljs-comment">// But Internet Explorer 11 doesn't support Array.includes()!</span>
<span class="hljs-comment">// A polyfill makes this work in older browsers</span>
</code></pre>
<h3 id="heading-why-are-polyfills-important">Why Are Polyfills Important?</h3>
<p><strong>1. Browser Compatibility</strong> Not all users update their browsers immediately. Some organizations are stuck with older versions due to legacy systems or policies.</p>
<p><strong>2. Progressive Enhancement</strong> You can use modern features while ensuring your site works for everyone.</p>
<p><strong>3. Backward Compatibility</strong> Write code using the latest standards without worrying about older environments.</p>
<p><strong>4. Transition Period</strong> During the adoption phase of new JavaScript features, polyfills keep your application accessible.</p>
<h3 id="heading-real-world-scenario">Real-World Scenario</h3>
<p>Let's say you're building a search feature and want to use <code>Array.includes()</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">searchUsers</span>(<span class="hljs-params">users, searchTerm</span>) </span>{
  <span class="hljs-keyword">return</span> users.filter(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> 
    user.name.toLowerCase().includes(searchTerm.toLowerCase())
  );
}

<span class="hljs-comment">// Works perfectly in modern browsers</span>
<span class="hljs-comment">// Crashes in IE11: "Object doesn't support property or method 'includes'"</span>
</code></pre>
<p>Without a polyfill, users on older browsers would see a broken search feature. With a polyfill, everyone gets a working application.</p>
<h2 id="heading-how-javascript-engines-work-and-why-polyfills-are-needed">How JavaScript Engines Work and Why Polyfills Are Needed</h2>
<h3 id="heading-javascript-engine-evolution">JavaScript Engine Evolution</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766945009980/e88772df-abe9-4b90-95b2-e30c4b140887.jpeg" alt class="image--center mx-auto" /></p>
<p>JavaScript engines (like V8 in Chrome, SpiderMonkey in Firefox, or Chakra in old Edge) are the programs that execute JavaScript code. Each engine implements JavaScript features based on ECMAScript specifications.</p>
<h3 id="heading-the-implementation-timeline">The Implementation Timeline</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766944949535/99e89491-b4b0-4de4-99af-80e94bb81748.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-feature-detection-flow">Feature Detection Flow</h3>
<p>Here's how polyfills work with feature detection:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766944828248/0db6a3a6-55e4-44c6-99de-f7399961465d.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-writing-your-own-polyfills-step-by-step">Writing Your Own Polyfills - Step by Step</h2>
<h3 id="heading-the-polyfill-pattern">The Polyfill Pattern</h3>
<p>Every polyfill follows this basic pattern:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// 1. Check if the feature exists</span>
<span class="hljs-keyword">if</span> (!SomeObject.someMethod) {
  <span class="hljs-comment">// 2. If not, define it</span>
  SomeObject.someMethod = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// 3. Implement the functionality</span>
  };
}
</code></pre>
<h3 id="heading-example-1-arrayincludes-polyfill">Example 1: Array.includes() Polyfill</h3>
<p>Let's write a polyfill for <code>Array.includes()</code>, introduced in ES2016:</p>
<p><strong>Step 1: Understand the specification</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// How Array.includes() should work:</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">2</span>);        <span class="hljs-comment">// true</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">4</span>);        <span class="hljs-comment">// false</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);     <span class="hljs-comment">// false (start from index 2)</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">NaN</span>].includes(<span class="hljs-literal">NaN</span>);    <span class="hljs-comment">// true (special case)</span>
</code></pre>
<p><strong>Step 2: Feature detection</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-comment">// Polyfill needed!</span>
}
</code></pre>
<p><strong>Step 3: Implement the polyfill</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-built_in">Array</span>.prototype.includes = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">searchElement, fromIndex</span>) </span>{
<span class="hljs-meta">    'use strict'</span>;

    <span class="hljs-comment">// Handle null/undefined</span>
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span> == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Array.prototype.includes called on null or undefined'</span>);
    }

    <span class="hljs-keyword">const</span> array = <span class="hljs-built_in">Object</span>(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">const</span> len = <span class="hljs-built_in">parseInt</span>(array.length) || <span class="hljs-number">0</span>;

    <span class="hljs-comment">// No elements to search</span>
    <span class="hljs-keyword">if</span> (len === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    <span class="hljs-comment">// Calculate starting index</span>
    <span class="hljs-keyword">let</span> startIndex = <span class="hljs-built_in">parseInt</span>(fromIndex) || <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> index;

    <span class="hljs-keyword">if</span> (startIndex &gt;= <span class="hljs-number">0</span>) {
      index = startIndex;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Negative index counts from end</span>
      index = len + startIndex;
      <span class="hljs-keyword">if</span> (index &lt; <span class="hljs-number">0</span>) {
        index = <span class="hljs-number">0</span>;
      }
    }

    <span class="hljs-comment">// Search for the element</span>
    <span class="hljs-keyword">while</span> (index &lt; len) {
      <span class="hljs-keyword">const</span> currentElement = array[index];

      <span class="hljs-comment">// Special case: NaN === NaN should be true</span>
      <span class="hljs-keyword">if</span> (searchElement === currentElement ||
          (searchElement !== searchElement &amp;&amp; currentElement !== currentElement)) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }

      index++;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  };
}

<span class="hljs-comment">// Test it!</span>
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">2</span>));           <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">4</span>));           <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">NaN</span>].includes(<span class="hljs-literal">NaN</span>));       <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>));        <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-example-2-objectassign-polyfill">Example 2: Object.assign() Polyfill</h3>
<p><code>Object.assign()</code> was introduced in ES2015 and is crucial for object manipulation:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Object</span>.assign !== <span class="hljs-string">'function'</span>) {
  <span class="hljs-built_in">Object</span>.assign = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">target</span>) </span>{
<span class="hljs-meta">    'use strict'</span>;

    <span class="hljs-keyword">if</span> (target == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Cannot convert undefined or null to object'</span>);
    }

    <span class="hljs-keyword">const</span> to = <span class="hljs-built_in">Object</span>(target);

    <span class="hljs-comment">// Loop through all source objects</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = <span class="hljs-number">1</span>; index &lt; <span class="hljs-built_in">arguments</span>.length; index++) {
      <span class="hljs-keyword">const</span> nextSource = <span class="hljs-built_in">arguments</span>[index];

      <span class="hljs-keyword">if</span> (nextSource != <span class="hljs-literal">null</span>) {
        <span class="hljs-comment">// Copy all enumerable own properties</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> nextKey <span class="hljs-keyword">in</span> nextSource) {
          <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }

    <span class="hljs-keyword">return</span> to;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">b</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">4</span> };
<span class="hljs-keyword">const</span> merged = <span class="hljs-built_in">Object</span>.assign({}, obj1, obj2);
<span class="hljs-built_in">console</span>.log(merged); <span class="hljs-comment">// { a: 1, b: 3, c: 4 }</span>
</code></pre>
<h3 id="heading-example-3-stringstartswith-polyfill">Example 3: String.startsWith() Polyfill</h3>
<p>A simple but useful string method from ES2015:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">String</span>.prototype.startsWith) {
  <span class="hljs-built_in">String</span>.prototype.startsWith = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">searchString, position</span>) </span>{
    position = position || <span class="hljs-number">0</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.substr(position, searchString.length) === searchString;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>.startsWith(<span class="hljs-string">'Hello'</span>));     <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>.startsWith(<span class="hljs-string">'World'</span>, <span class="hljs-number">6</span>));  <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>.startsWith(<span class="hljs-string">'hello'</span>));     <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-example-4-promisefinally-polyfill">Example 4: Promise.finally() Polyfill</h3>
<p>For handling promise cleanup, introduced in ES2018:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Promise</span>.prototype.finally !== <span class="hljs-string">'function'</span>) {
  <span class="hljs-built_in">Promise</span>.prototype.finally = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">constructor</span> = this.<span class="hljs-keyword">constructor</span>;

    return this.then(
      // Success handler
      value =&gt; <span class="hljs-keyword">constructor</span>.resolve(callback()).then(() =&gt; value),
      // Error handler
      reason =&gt; <span class="hljs-keyword">constructor</span>.resolve(callback()).then(() =&gt; {
        <span class="hljs-keyword">throw</span> reason;
      })
    );
  };
}

<span class="hljs-comment">// Usage</span>
fetch(<span class="hljs-string">'/api/data'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error))
  .finally(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Cleanup: Hide loading spinner'</span>));
</code></pre>
<h2 id="heading-common-polyfills-every-developer-should-know">Common Polyfills Every Developer Should Know</h2>
<h3 id="heading-1-array-methods-polyfills">1. Array Methods Polyfills</h3>
<p><strong>Array.find()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.find) {
  <span class="hljs-built_in">Array</span>.prototype.find = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">predicate</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span> == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Array.prototype.find called on null or undefined'</span>);
    }
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> predicate !== <span class="hljs-string">'function'</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'predicate must be a function'</span>);
    }

    <span class="hljs-keyword">const</span> list = <span class="hljs-built_in">Object</span>(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">const</span> length = list.length &gt;&gt;&gt; <span class="hljs-number">0</span>;
    <span class="hljs-keyword">const</span> thisArg = <span class="hljs-built_in">arguments</span>[<span class="hljs-number">1</span>];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) {
      <span class="hljs-keyword">const</span> value = list[i];
      <span class="hljs-keyword">if</span> (predicate.call(thisArg, value, i, list)) {
        <span class="hljs-keyword">return</span> value;
      }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Charlie'</span> }
];

<span class="hljs-keyword">const</span> user = users.find(<span class="hljs-function"><span class="hljs-params">u</span> =&gt;</span> u.id === <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(user); <span class="hljs-comment">// { id: 2, name: 'Bob' }</span>
</code></pre>
<p><strong>Array.from()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.from) {
  <span class="hljs-built_in">Array</span>.from = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arrayLike</span>) </span>{
    <span class="hljs-keyword">const</span> items = <span class="hljs-built_in">Object</span>(arrayLike);

    <span class="hljs-keyword">if</span> (arrayLike == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Array.from requires an array-like object'</span>);
    }

    <span class="hljs-keyword">const</span> len = items.length &gt;&gt;&gt; <span class="hljs-number">0</span>;
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(len);

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; len; i++) {
      result[i] = items[i];
    }

    <span class="hljs-keyword">return</span> result;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> nodeList = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> array = <span class="hljs-built_in">Array</span>.from(nodeList);
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.isArray(array)); <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-2-object-methods-polyfills">2. Object Methods Polyfills</h3>
<p><strong>Object.keys()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Object</span>.keys) {
  <span class="hljs-built_in">Object</span>.keys = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (obj !== <span class="hljs-built_in">Object</span>(obj)) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Object.keys called on non-object'</span>);
    }

    <span class="hljs-keyword">const</span> keys = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.prototype.hasOwnProperty.call(obj, key)) {
        keys.push(key);
      }
    }

    <span class="hljs-keyword">return</span> keys;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">'NYC'</span> };
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(person)); <span class="hljs-comment">// ['name', 'age', 'city']</span>
</code></pre>
<p><strong>Object.values()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Object</span>.values) {
  <span class="hljs-built_in">Object</span>.values = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (obj !== <span class="hljs-built_in">Object</span>(obj)) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Object.values called on non-object'</span>);
    }

    <span class="hljs-keyword">const</span> values = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.prototype.hasOwnProperty.call(obj, key)) {
        values.push(obj[key]);
      }
    }

    <span class="hljs-keyword">return</span> values;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> scores = { <span class="hljs-attr">math</span>: <span class="hljs-number">95</span>, <span class="hljs-attr">science</span>: <span class="hljs-number">87</span>, <span class="hljs-attr">english</span>: <span class="hljs-number">92</span> };
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.values(scores)); <span class="hljs-comment">// [95, 87, 92]</span>
</code></pre>
<h3 id="heading-3-string-methods-polyfills">3. String Methods Polyfills</h3>
<p><strong>String.repeat()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">String</span>.prototype.repeat) {
  <span class="hljs-built_in">String</span>.prototype.repeat = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">count</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span> == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'String.prototype.repeat called on null or undefined'</span>);
    }

    <span class="hljs-keyword">const</span> str = <span class="hljs-built_in">String</span>(<span class="hljs-built_in">this</span>);
    count = <span class="hljs-built_in">Math</span>.floor(count);

    <span class="hljs-keyword">if</span> (count &lt; <span class="hljs-number">0</span> || count === <span class="hljs-literal">Infinity</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">RangeError</span>(<span class="hljs-string">'Invalid count value'</span>);
    }

    <span class="hljs-keyword">if</span> (count === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-string">''</span>;
    }

    <span class="hljs-keyword">let</span> result = <span class="hljs-string">''</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; count; i++) {
      result += str;
    }

    <span class="hljs-keyword">return</span> result;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'*'</span>.repeat(<span class="hljs-number">5</span>));      <span class="hljs-comment">// "*****"</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>.repeat(<span class="hljs-number">3</span>));  <span class="hljs-comment">// "HelloHelloHello"</span>
</code></pre>
<h3 id="heading-4-function-methods-polyfills">4. Function Methods Polyfills</h3>
<p><strong>Function.bind()</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Function</span>.prototype.bind) {
  <span class="hljs-built_in">Function</span>.prototype.bind = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">context</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">this</span> !== <span class="hljs-string">'function'</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Function.prototype.bind called on non-function'</span>);
    }

    <span class="hljs-keyword">const</span> fn = <span class="hljs-built_in">this</span>;
    <span class="hljs-keyword">const</span> args = <span class="hljs-built_in">Array</span>.prototype.slice.call(<span class="hljs-built_in">arguments</span>, <span class="hljs-number">1</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">const</span> finalArgs = args.concat(<span class="hljs-built_in">Array</span>.prototype.slice.call(<span class="hljs-built_in">arguments</span>));
      <span class="hljs-keyword">return</span> fn.apply(context, finalArgs);
    };
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = {
  <span class="hljs-attr">x</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">getX</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.x;
  }
};

<span class="hljs-keyword">const</span> unboundGetX = <span class="hljs-built_in">module</span>.getX;
<span class="hljs-built_in">console</span>.log(unboundGetX()); <span class="hljs-comment">// undefined (or error in strict mode)</span>

<span class="hljs-keyword">const</span> boundGetX = unboundGetX.bind(<span class="hljs-built_in">module</span>);
<span class="hljs-built_in">console</span>.log(boundGetX()); <span class="hljs-comment">// 42</span>
</code></pre>
<h2 id="heading-best-practices-for-using-polyfills">Best Practices for Using Polyfills</h2>
<h3 id="heading-1-always-feature-detect-first">1. Always Feature-Detect First</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// GOOD ✓</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-comment">// Add polyfill</span>
}

<span class="hljs-comment">// BAD ✗</span>
<span class="hljs-comment">// Blindly adding polyfills without checking</span>
<span class="hljs-built_in">Array</span>.prototype.includes = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">/*...*/</span> };
</code></pre>
<h3 id="heading-2-use-established-polyfill-libraries">2. Use Established Polyfill Libraries</h3>
<p>For production, consider using well-tested libraries:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// core-js - Most comprehensive</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/stable'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'regenerator-runtime/runtime'</span>;

<span class="hljs-comment">// Or selectively import what you need</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/features/array/includes'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/features/promise/finally'</span>;
</code></pre>
<h3 id="heading-3-use-polyfill-services">3. Use Polyfill Services</h3>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Polyfill.io - Serves only needed polyfills based on user agent --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Or specify features --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js?features=Array.prototype.includes,Promise.prototype.finally"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<h3 id="heading-4-document-your-polyfills">4. Document Your Polyfills</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
 * Polyfill for Array.prototype.includes
 * <span class="hljs-doctag">@see </span>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
 * <span class="hljs-doctag">@compatibility </span>IE 11, Edge &lt; 14
 */</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-comment">// Implementation</span>
}
</code></pre>
<h3 id="heading-5-test-in-target-browsers">5. Test in Target Browsers</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Use tools like:</span>
<span class="hljs-comment">// - BrowserStack</span>
<span class="hljs-comment">// - Sauce Labs</span>
<span class="hljs-comment">// - LambdaTest</span>
<span class="hljs-comment">// To verify polyfills work in actual old browsers</span>
</code></pre>
<h2 id="heading-polyfills-vs-transpilers">Polyfills vs Transpilers</h2>
<h3 id="heading-key-differences">Key Differences</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Polyfills</td><td>Transpilers</td></tr>
</thead>
<tbody>
<tr>
<td><strong>What they handle</strong></td><td>Runtime features (methods, APIs)</td><td>Syntax features (arrow functions, classes)</td></tr>
<tr>
<td><strong>When they run</strong></td><td>At runtime in the browser</td><td>At build time before deployment</td></tr>
<tr>
<td><strong>Example tools</strong></td><td>core-js, polyfill.io</td><td>Babel, TypeScript</td></tr>
<tr>
<td><strong>File size impact</strong></td><td>Adds JavaScript code</td><td>Transforms existing code</td></tr>
<tr>
<td><strong>Use case</strong></td><td><code>Array.includes()</code>, <code>Promise</code></td><td><code>async/await</code>, <code>?.</code> optional chaining</td></tr>
</tbody>
</table>
</div><h3 id="heading-example-what-needs-what">Example: What Needs What?</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// NEEDS TRANSPILER (syntax feature)</span>
<span class="hljs-keyword">const</span> greet = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{ <span class="hljs-keyword">constructor</span>(name) { <span class="hljs-built_in">this</span>.name = name; } }
<span class="hljs-keyword">const</span> value = obj?.property;

<span class="hljs-comment">// NEEDS POLYFILL (runtime feature)</span>
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].includes(<span class="hljs-number">2</span>);
<span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">42</span>);
<span class="hljs-built_in">Object</span>.assign({}, obj1, obj2);

<span class="hljs-comment">// NEEDS BOTH</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{  <span class="hljs-comment">// Transpiler for async/await</span>
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);  <span class="hljs-comment">// Polyfill for fetch</span>
  <span class="hljs-keyword">return</span> response.json();
}
</code></pre>
<h2 id="heading-building-a-smart-polyfill-loader">Building a Smart Polyfill Loader</h2>
<p>Here's a pattern for conditionally loading polyfills:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// polyfill-loader.js</span>
<span class="hljs-keyword">const</span> requiredFeatures = {
  <span class="hljs-string">'Promise'</span>: <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Promise</span> !== <span class="hljs-string">'undefined'</span>,
  <span class="hljs-string">'Array.includes'</span>: <span class="hljs-built_in">Array</span>.prototype.includes,
  <span class="hljs-string">'Object.assign'</span>: <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Object</span>.assign === <span class="hljs-string">'function'</span>,
  <span class="hljs-string">'fetch'</span>: <span class="hljs-keyword">typeof</span> fetch === <span class="hljs-string">'function'</span>
};

<span class="hljs-keyword">const</span> missingFeatures = <span class="hljs-built_in">Object</span>.keys(requiredFeatures)
  .filter(<span class="hljs-function"><span class="hljs-params">feature</span> =&gt;</span> !requiredFeatures[feature]);

<span class="hljs-keyword">if</span> (missingFeatures.length &gt; <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Loading polyfills for:'</span>, missingFeatures.join(<span class="hljs-string">', '</span>));

  <span class="hljs-comment">// Load polyfill bundle</span>
  <span class="hljs-keyword">const</span> script = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'script'</span>);
  script.src = <span class="hljs-string">'/polyfills/bundle.js'</span>;
  <span class="hljs-built_in">document</span>.head.appendChild(script);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All features supported, no polyfills needed!'</span>);
}
</code></pre>
<h2 id="heading-real-world-case-study">Real-World Case Study</h2>
<h3 id="heading-the-problem">The Problem</h3>
<p>A company needed to support IE11 for enterprise clients while using modern JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Modern code they wanted to write</span>
<span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/api/users'</span>).then(<span class="hljs-function"><span class="hljs-params">r</span> =&gt;</span> r.json());
<span class="hljs-keyword">const</span> activeUsers = users.filter(<span class="hljs-function"><span class="hljs-params">u</span> =&gt;</span> u.status === <span class="hljs-string">'active'</span>);
<span class="hljs-keyword">const</span> hasAdmin = activeUsers.some(<span class="hljs-function"><span class="hljs-params">u</span> =&gt;</span> u.role?.includes(<span class="hljs-string">'admin'</span>));
</code></pre>
<h3 id="heading-the-solution">The Solution</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// 1. Install core-js and regenerator-runtime</span>
<span class="hljs-comment">// npm install core-js regenerator-runtime</span>

<span class="hljs-comment">// 2. Import at app entry point</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/stable'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'regenerator-runtime/runtime'</span>;

<span class="hljs-comment">// 3. Configure Babel to use polyfills</span>
<span class="hljs-comment">// babel.config.js</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">presets</span>: [
    [<span class="hljs-string">'@babel/preset-env'</span>, {
      <span class="hljs-attr">useBuiltIns</span>: <span class="hljs-string">'usage'</span>,
      <span class="hljs-attr">corejs</span>: <span class="hljs-number">3</span>,
      <span class="hljs-attr">targets</span>: {
        <span class="hljs-attr">ie</span>: <span class="hljs-string">'11'</span>
      }
    }]
  ]
};

<span class="hljs-comment">// 4. Add fetch polyfill separately</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'whatwg-fetch'</span>;

<span class="hljs-comment">// Now the code works in IE11!</span>
</code></pre>
<h3 id="heading-the-results">The Results</h3>
<ul>
<li><p>✅ Code works in IE11 and all modern browsers</p>
</li>
<li><p>✅ Only ~50KB added to bundle (gzipped)</p>
</li>
<li><p>✅ Modern browsers use native features (faster)</p>
</li>
<li><p>✅ Maintainable codebase using latest JavaScript</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Polyfills are essential tools for modern web development, allowing you to use the latest JavaScript features while maintaining compatibility with older browsers. By understanding how to write and use polyfills effectively, you can:</p>
<ul>
<li><p><strong>Write modern code</strong> without worrying about browser support</p>
</li>
<li><p><strong>Maintain backward compatibility</strong> for all users</p>
</li>
<li><p><strong>Understand JavaScript better</strong> by implementing features yourself</p>
</li>
<li><p><strong>Make informed decisions</strong> about when to use polyfills vs transpilers</p>
</li>
</ul>
<hr />
<p><strong>Key Takeaways:</strong></p>
<ol>
<li><p><strong>Always feature-detect</strong> before applying polyfills</p>
</li>
<li><p><strong>Use established libraries</strong> like core-js for production</p>
</li>
<li><p><strong>Understand the difference</strong> between polyfills and transpilers</p>
</li>
<li><p><strong>Test in real browsers</strong> to verify compatibility</p>
</li>
<li><p><strong>Document your support targets</strong> and polyfill choices</p>
</li>
<li><p><strong>Keep bundles small</strong> by only including needed polyfills</p>
</li>
</ol>
<p>Remember: The goal is to provide a great user experience for everyone, regardless of their browser. Polyfills help you achieve that goal while embracing modern JavaScript features.</p>
<p>Happy coding! 🚀</p>
<hr />
<p><strong>Further Reading:</strong></p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Polyfill">MDN Polyfill Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/zloirock/core-js">Core-js Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://caniuse.com/">Can I Use - Browser Compatibility Tables</a></p>
</li>
<li><p><a target="_blank" href="https://polyfill.io/">Polyfill.io Service</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Prototype - The Backbone of JavaScript Objects]]></title><description><![CDATA[JavaScript's prototype system is one of its most powerful yet misunderstood features. Unlike classical object-oriented languages that use classes as blueprints, JavaScript uses prototypes to implement inheritance and share functionality between objec...]]></description><link>https://blogs.swarupdas.dev/prototype-the-backbone-of-javascript-objects</link><guid isPermaLink="true">https://blogs.swarupdas.dev/prototype-the-backbone-of-javascript-objects</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[prototyping]]></category><category><![CDATA[prototypes]]></category><category><![CDATA[prototype chain]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Sun, 28 Dec 2025 17:54:59 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript's prototype system is one of its most powerful yet misunderstood features. Unlike classical object-oriented languages that use classes as blueprints, JavaScript uses prototypes to implement inheritance and share functionality between objects. Let's dive deep into this fundamental concept.</p>
<h2 id="heading-understanding-prototypes-in-javascript">Understanding Prototypes in JavaScript</h2>
<h3 id="heading-the-blueprint-analogy">The Blueprint Analogy</h3>
<p>Think of prototypes like architectural blueprints for houses. When you build a house, you don't recreate the blueprint each time—you reference the original design. Similarly, when you create objects in JavaScript, they don't duplicate all methods and properties. Instead, they reference a shared prototype object.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// When you create an array</span>
<span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// It doesn't copy methods like push, pop, map</span>
<span class="hljs-comment">// Instead, it links to Array.prototype</span>
<span class="hljs-built_in">console</span>.log(myArray.__proto__ === <span class="hljs-built_in">Array</span>.prototype); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// So when you call a method</span>
myArray.push(<span class="hljs-number">4</span>);
<span class="hljs-comment">// JavaScript looks up the prototype chain to find 'push'</span>
</code></pre>
<h3 id="heading-what-exactly-is-a-prototype">What Exactly is a Prototype?</h3>
<p>Every JavaScript object has an internal property called <code>[[Prototype]]</code> (accessed via <code>__proto__</code> or <code>Object.getPrototypeOf()</code>). This property is a reference to another object, forming a chain that JavaScript traverses when looking for properties or methods.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  greet() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>;
  }
};

<span class="hljs-keyword">const</span> john = <span class="hljs-built_in">Object</span>.create(person);
john.name = <span class="hljs-string">'John'</span>;

<span class="hljs-built_in">console</span>.log(john.greet()); <span class="hljs-comment">// "Hello, I'm John"</span>
<span class="hljs-comment">// john doesn't have greet(), but its prototype does!</span>
</code></pre>
<h3 id="heading-constructor-functions-and-the-prototype-property">Constructor Functions and the <code>prototype</code> Property</h3>
<p>When you create a constructor function, JavaScript automatically gives it a <code>prototype</code> property. This property becomes the prototype of all instances created with that constructor.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Car</span>(<span class="hljs-params">brand, model</span>) </span>{
  <span class="hljs-built_in">this</span>.brand = brand;
  <span class="hljs-built_in">this</span>.model = model;
}

<span class="hljs-comment">// Adding methods to the prototype</span>
Car.prototype.getInfo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>;
};

<span class="hljs-keyword">const</span> tesla = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">'Tesla'</span>, <span class="hljs-string">'Model 3'</span>);
<span class="hljs-keyword">const</span> bmw = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'X5'</span>);

<span class="hljs-built_in">console</span>.log(tesla.getInfo()); <span class="hljs-comment">// "Tesla Model 3"</span>
<span class="hljs-built_in">console</span>.log(bmw.getInfo()); <span class="hljs-comment">// "BMW X5"</span>

<span class="hljs-comment">// Both instances share the same method</span>
<span class="hljs-built_in">console</span>.log(tesla.getInfo === bmw.getInfo); <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-the-prototype-chain-how-inheritance-works">The Prototype Chain - How Inheritance Works</h2>
<p>The prototype chain is JavaScript's mechanism for inheritance. When you try to access a property on an object, JavaScript follows this lookup process:</p>
<ol>
<li><p>Check if the property exists on the object itself</p>
</li>
<li><p>If not, check the object's prototype</p>
</li>
<li><p>If not, check the prototype's prototype</p>
</li>
<li><p>Continue until reaching <code>Object.prototype</code></p>
</li>
<li><p>If still not found, return <code>undefined</code></p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

Animal.prototype.speak = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> makes a sound`</span>;
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">name, breed</span>) </span>{
  Animal.call(<span class="hljs-built_in">this</span>, name); <span class="hljs-comment">// Call parent constructor</span>
  <span class="hljs-built_in">this</span>.breed = breed;
}

<span class="hljs-comment">// Set up inheritance</span>
Dog.prototype = <span class="hljs-built_in">Object</span>.create(Animal.prototype);
Dog.prototype.constructor = Dog;

<span class="hljs-comment">// Add Dog-specific method</span>
Dog.prototype.bark = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> barks!`</span>;
};

<span class="hljs-keyword">const</span> buddy = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Buddy'</span>, <span class="hljs-string">'Golden Retriever'</span>);

<span class="hljs-built_in">console</span>.log(buddy.name);       <span class="hljs-comment">// "Buddy" (own property)</span>
<span class="hljs-built_in">console</span>.log(buddy.bark());     <span class="hljs-comment">// "Buddy barks!" (Dog.prototype)</span>
<span class="hljs-built_in">console</span>.log(buddy.speak());    <span class="hljs-comment">// "Buddy makes a sound" (Animal.prototype)</span>
<span class="hljs-built_in">console</span>.log(buddy.toString()); <span class="hljs-comment">// "[object Object]" (Object.prototype)</span>
</code></pre>
<h3 id="heading-visualizing-the-prototype-chain">Visualizing the Prototype Chain</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766944422088/bac123df-8082-4966-b41b-f7bd12067f41.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-classical-vs-prototype-based-inheritance">Classical vs Prototype-Based Inheritance</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Classical Inheritance</td><td>Prototype-Based Inheritance</td></tr>
</thead>
<tbody>
<tr>
<td>Classes are blueprints</td><td>Objects inherit from objects</td></tr>
<tr>
<td>Instances are copies of class structure</td><td>Instances link to prototype objects</td></tr>
<tr>
<td>Inheritance through class hierarchy</td><td>Inheritance through prototype chain</td></tr>
<tr>
<td>Static structure defined at compile time</td><td>Dynamic structure can change at runtime</td></tr>
<tr>
<td>Used in Java, C++, C#</td><td>Used in JavaScript, Lua</td></tr>
</tbody>
</table>
</div><h2 id="heading-comparing-prototype-access-methods">Comparing Prototype Access Methods</h2>
<p>JavaScript provides several ways to work with prototypes. Let's compare them:</p>
<h3 id="heading-1-objectcreate">1. <code>Object.create()</code></h3>
<p>The modern, recommended way to create objects with a specific prototype.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> animal = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'Unknown'</span>,
  describe() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`This is a <span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span>`</span>;
  }
};

<span class="hljs-keyword">const</span> cat = <span class="hljs-built_in">Object</span>.create(animal);
cat.type = <span class="hljs-string">'Cat'</span>;

<span class="hljs-built_in">console</span>.log(cat.describe()); <span class="hljs-comment">// "This is a Cat"</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(cat) === animal); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>Pros:</strong> Clean, explicit, widely supported<br /><strong>Use case:</strong> When you want to create an object that inherits from another object</p>
<h3 id="heading-2-proto-property">2. <code>__proto__</code> Property</h3>
<p>Direct access to an object's prototype (deprecated but still widely used).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dog = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Rex'</span> };
<span class="hljs-keyword">const</span> puppy = { <span class="hljs-attr">age</span>: <span class="hljs-number">1</span> };

puppy.__proto__ = dog;
<span class="hljs-built_in">console</span>.log(puppy.name); <span class="hljs-comment">// "Rex"</span>

<span class="hljs-comment">// Better alternative:</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(puppy, dog);
</code></pre>
<p><strong>Pros:</strong> Simple, direct access<br /><strong>Cons:</strong> Deprecated, performance issues<br /><strong>Use case:</strong> Debugging or legacy code only</p>
<h3 id="heading-3-prototype-property">3. <code>prototype</code> Property</h3>
<p>Used with constructor functions to define shared methods.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Vehicle</span>(<span class="hljs-params">type</span>) </span>{
  <span class="hljs-built_in">this</span>.type = type;
}

Vehicle.prototype.move = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span> is moving`</span>;
};

<span class="hljs-keyword">const</span> car = <span class="hljs-keyword">new</span> Vehicle(<span class="hljs-string">'Car'</span>);
<span class="hljs-built_in">console</span>.log(car.move()); <span class="hljs-comment">// "Car is moving"</span>
</code></pre>
<p><strong>Pros:</strong> Memory efficient, traditional pattern<br /><strong>Use case:</strong> Constructor functions, before ES6 classes</p>
<h3 id="heading-modern-approach-with-es6-classes">Modern Approach with ES6 Classes</h3>
<p>ES6 classes are syntactic sugar over prototypes:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> </span>{
  <span class="hljs-keyword">constructor</span>(color) {
    <span class="hljs-built_in">this</span>.color = color;
  }

  describe() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`A <span class="hljs-subst">${<span class="hljs-built_in">this</span>.color}</span> shape`</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Shape</span> </span>{
  <span class="hljs-keyword">constructor</span>(color, radius) {
    <span class="hljs-built_in">super</span>(color);
    <span class="hljs-built_in">this</span>.radius = radius;
  }

  getArea() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * <span class="hljs-built_in">this</span>.radius ** <span class="hljs-number">2</span>;
  }
}

<span class="hljs-keyword">const</span> redCircle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-string">'red'</span>, <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(redCircle.describe()); <span class="hljs-comment">// "A red shape"</span>
<span class="hljs-built_in">console</span>.log(redCircle.getArea().toFixed(<span class="hljs-number">2</span>)); <span class="hljs-comment">// "78.54"</span>

<span class="hljs-comment">// Under the hood, it's still prototypes!</span>
<span class="hljs-built_in">console</span>.log(redCircle.__proto__ === Circle.prototype); <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-modifying-prototypes-dos-and-donts">Modifying Prototypes - Do's and Don'ts</h2>
<h3 id="heading-dos">✅ Do's</h3>
<p><strong>1. Add methods to your own constructor prototypes</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

User.prototype.sayHello = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>;
};
</code></pre>
<p><strong>2. Use Object.create() for delegation</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> methods = {
  log() { <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.value); }
};

<span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">Object</span>.create(methods);
obj.value = <span class="hljs-number">42</span>;
</code></pre>
<p><strong>3. Check property ownership</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span> };
person.__proto__.age = <span class="hljs-number">30</span>;

<span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'name'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'age'</span>));  <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-donts">❌ Don'ts</h3>
<p><strong>1. Never modify built-in prototypes (except for polyfills)</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// BAD - Don't do this!</span>
<span class="hljs-built_in">Array</span>.prototype.myMethod = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// This affects ALL arrays everywhere</span>
};

<span class="hljs-comment">// If you must (for polyfills), check first:</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-built_in">Array</span>.prototype.includes = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">searchElement</span>) </span>{
    <span class="hljs-comment">// Polyfill implementation</span>
  };
}
</code></pre>
<p><strong>2. Avoid setting proto in production</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// BAD - Performance killer</span>
obj.__proto__ = somePrototype;

<span class="hljs-comment">// GOOD - Use these instead</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(obj, somePrototype);
<span class="hljs-comment">// or better yet:</span>
<span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">Object</span>.create(somePrototype);
</code></pre>
<p><strong>3. Don't create very long prototype chains</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// BAD - Too many levels</span>
A.prototype = <span class="hljs-built_in">Object</span>.create(B.prototype);
B.prototype = <span class="hljs-built_in">Object</span>.create(C.prototype);
C.prototype = <span class="hljs-built_in">Object</span>.create(D.prototype);
D.prototype = <span class="hljs-built_in">Object</span>.create(E.prototype);

<span class="hljs-comment">// GOOD - Keep it shallow, use composition instead</span>
</code></pre>
<h3 id="heading-performance-considerations">Performance Considerations</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Slow: Property lookup travels up the chain</span>
<span class="hljs-keyword">const</span> deep = <span class="hljs-built_in">Object</span>.create(
  <span class="hljs-built_in">Object</span>.create(
    <span class="hljs-built_in">Object</span>.create(
      <span class="hljs-built_in">Object</span>.create({ <span class="hljs-attr">value</span>: <span class="hljs-number">42</span> })
    )
  )
);

<span class="hljs-built_in">console</span>.log(deep.value); <span class="hljs-comment">// Has to traverse 4 levels</span>

<span class="hljs-comment">// Fast: Direct property access</span>
<span class="hljs-keyword">const</span> shallow = { <span class="hljs-attr">value</span>: <span class="hljs-number">42</span> };
<span class="hljs-built_in">console</span>.log(shallow.value); <span class="hljs-comment">// Immediate access</span>
</code></pre>
<h2 id="heading-practical-examples">Practical Examples</h2>
<h3 id="heading-example-1-creating-a-simple-plugin-system">Example 1: Creating a Simple Plugin System</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Plugin = {
  init() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> initialized`</span>);
  }
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPlugin</span>(<span class="hljs-params">name, functionality</span>) </span>{
  <span class="hljs-keyword">const</span> plugin = <span class="hljs-built_in">Object</span>.create(Plugin);
  plugin.name = name;
  plugin.execute = functionality;
  <span class="hljs-keyword">return</span> plugin;
}

<span class="hljs-keyword">const</span> logger = createPlugin(<span class="hljs-string">'Logger'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">msg</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`[LOG]: <span class="hljs-subst">${msg}</span>`</span>);
});

logger.init(); <span class="hljs-comment">// "Logger initialized"</span>
logger.execute(<span class="hljs-string">'Hello World'</span>); <span class="hljs-comment">// "[LOG]: Hello World"</span>
</code></pre>
<h3 id="heading-example-2-implementing-method-sharing">Example 2: Implementing Method Sharing</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> mathOperations = {
  add(a, b) { <span class="hljs-keyword">return</span> a + b; },
  subtract(a, b) { <span class="hljs-keyword">return</span> a - b; }
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Calculator</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.history = [];
}

Calculator.prototype = <span class="hljs-built_in">Object</span>.create(mathOperations);
Calculator.prototype.calculate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">operation, a, b</span>) </span>{
  <span class="hljs-keyword">const</span> result = <span class="hljs-built_in">this</span>[operation](a, b);
  <span class="hljs-built_in">this</span>.history.push(<span class="hljs-string">`<span class="hljs-subst">${operation}</span>(<span class="hljs-subst">${a}</span>, <span class="hljs-subst">${b}</span>) = <span class="hljs-subst">${result}</span>`</span>);
  <span class="hljs-keyword">return</span> result;
};

<span class="hljs-keyword">const</span> calc = <span class="hljs-keyword">new</span> Calculator(<span class="hljs-string">'MyCalc'</span>);
<span class="hljs-built_in">console</span>.log(calc.calculate(<span class="hljs-string">'add'</span>, <span class="hljs-number">5</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 8</span>
<span class="hljs-built_in">console</span>.log(calc.history); <span class="hljs-comment">// ["add(5, 3) = 8"]</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Prototypes are the foundation of JavaScript's object model. Understanding them helps you:</p>
<ul>
<li><p>Write more memory-efficient code by sharing methods</p>
</li>
<li><p>Understand how inheritance works in JavaScript</p>
</li>
<li><p>Debug complex object hierarchies</p>
</li>
<li><p>Make informed decisions about using classes vs prototypes</p>
</li>
<li><p>Avoid common pitfalls when extending objects</p>
</li>
</ul>
<p>While ES6 classes provide a more familiar syntax, prototypes remain the underlying mechanism. Mastering prototypes gives you deeper insight into how JavaScript truly works under the hood.</p>
<hr />
<p><strong>Key Takeaways:</strong></p>
<ul>
<li><p>Every object has a prototype (except Object.prototype)</p>
</li>
<li><p>Prototypes enable inheritance through delegation</p>
</li>
<li><p>Use Object.create() for modern prototype manipulation</p>
</li>
<li><p>Avoid modifying built-in prototypes</p>
</li>
<li><p>ES6 classes are syntactic sugar over prototypes</p>
</li>
<li><p>Keep prototype chains shallow for better performance</p>
</li>
</ul>
<p>Happy coding! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Prototypes & Inheritance in JavaScript: The Blueprint Analogy]]></title><description><![CDATA[Ever wondered how JavaScript objects share behaviors and properties? Let me take you on a journey through one of JavaScript's most powerful yet misunderstood features: prototypes and inheritance.
The Blueprint Story: Understanding Prototypes
Imagine ...]]></description><link>https://blogs.swarupdas.dev/understanding-prototypes-and-inheritance-in-javascript-the-blueprint-analogy</link><guid isPermaLink="true">https://blogs.swarupdas.dev/understanding-prototypes-and-inheritance-in-javascript-the-blueprint-analogy</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[prototype]]></category><category><![CDATA[prototypeal-inheritance]]></category><dc:creator><![CDATA[Swarup Das]]></dc:creator><pubDate>Sun, 28 Dec 2025 17:47:14 GMT</pubDate><content:encoded><![CDATA[<p>Ever wondered how JavaScript objects share behaviors and properties? Let me take you on a journey through one of JavaScript's most powerful yet misunderstood features: prototypes and inheritance.</p>
<h2 id="heading-the-blueprint-story-understanding-prototypes">The Blueprint Story: Understanding Prototypes</h2>
<p>Imagine you're an architect designing houses. You don't build each house from scratch—you create a <strong>blueprint</strong> that contains all the common features: doors, windows, plumbing systems. Each house built from this blueprint shares these features, but can also have its own unique characteristics.</p>
<p>This is exactly how JavaScript prototypes work!</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// The "Blueprint" - Constructor Function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">House</span>(<span class="hljs-params">address, color</span>) </span>{
    <span class="hljs-built_in">this</span>.address = address;
    <span class="hljs-built_in">this</span>.color = color;
}

<span class="hljs-comment">// Shared features (methods) on the prototype</span>
House.prototype.openDoor = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Opening door at <span class="hljs-subst">${<span class="hljs-built_in">this</span>.address}</span>`</span>);
};

House.prototype.paintWall = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">newColor</span>) </span>{
    <span class="hljs-built_in">this</span>.color = newColor;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`House painted <span class="hljs-subst">${newColor}</span>`</span>);
};

<span class="hljs-comment">// Creating houses from the blueprint</span>
<span class="hljs-keyword">const</span> house1 = <span class="hljs-keyword">new</span> House(<span class="hljs-string">"123 Main St"</span>, <span class="hljs-string">"blue"</span>);
<span class="hljs-keyword">const</span> house2 = <span class="hljs-keyword">new</span> House(<span class="hljs-string">"456 Oak Ave"</span>, <span class="hljs-string">"red"</span>);

house1.openDoor(); <span class="hljs-comment">// "Opening door at 123 Main St"</span>
house2.openDoor(); <span class="hljs-comment">// "Opening door at 456 Oak Ave"</span>
</code></pre>
<h3 id="heading-what-happens-when-two-objects-are-created-from-one-class">What Happens When Two Objects Are Created from One Class?</h3>
<p>When you create <code>house1</code> and <code>house2</code> from the same constructor:</p>
<ol>
<li><p><strong>Each object gets its own property storage</strong> - <code>house1.address</code> and <code>house2.address</code> are separate</p>
</li>
<li><p><strong>They share the same prototype methods</strong> - Both point to <code>House.prototype.openDoor</code> (same memory location!)</p>
</li>
<li><p><strong>Changes to the prototype affect all instances</strong></p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(house1.openDoor === house2.openDoor); <span class="hljs-comment">// true (same function!)</span>

<span class="hljs-comment">// Adding a new method to the prototype</span>
House.prototype.lockDoor = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Locking door at <span class="hljs-subst">${<span class="hljs-built_in">this</span>.address}</span>`</span>);
};

<span class="hljs-comment">// Both houses can now use it!</span>
house1.lockDoor(); <span class="hljs-comment">// Works!</span>
house2.lockDoor(); <span class="hljs-comment">// Works!</span>
</code></pre>
<h2 id="heading-the-prototype-chain-the-family-tree">The Prototype Chain: The Family Tree</h2>
<p>Think of prototypes like a <strong>family tree of genetic traits</strong>. Your traits come from your parents, their traits come from grandparents, and so on.</p>
<pre><code class="lang-plaintext">house1 → House.prototype → Object.prototype → null
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Demonstration of the prototype chain</span>
<span class="hljs-built_in">console</span>.log(house1.toString()); <span class="hljs-comment">// Inherited from Object.prototype</span>

<span class="hljs-comment">// The chain lookup process</span>
house1.openDoor();
<span class="hljs-comment">// 1. Does house1 have openDoor? No</span>
<span class="hljs-comment">// 2. Does House.prototype have openDoor? Yes! Execute it.</span>
</code></pre>
<h2 id="heading-prototype-vs-proto-the-confusion-cleared"><code>prototype</code> vs <code>__proto__</code>: The Confusion Cleared</h2>
<p>This is where many developers get confused. Let's break it down with our blueprint analogy:</p>
<ul>
<li><p><code>prototype</code>: The blueprint itself (only on constructor functions)</p>
</li>
<li><p><code>__proto__</code>: The reference each house keeps to its blueprint</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}

Animal.prototype.speak = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> makes a sound`</span>);
};

<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">"Rex"</span>);

<span class="hljs-comment">// PROTOTYPE - the blueprint (only on constructor)</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> Animal.prototype); <span class="hljs-comment">// "object"</span>
<span class="hljs-built_in">console</span>.log(Animal.prototype.speak); <span class="hljs-comment">// function</span>

<span class="hljs-comment">// __PROTO__ - the reference to the blueprint (on instances)</span>
<span class="hljs-built_in">console</span>.log(dog.__proto__ === Animal.prototype); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(dog.prototype); <span class="hljs-comment">// undefined (instances don't have prototype)</span>
</code></pre>
<h3 id="heading-visual-comparison-prototype-vs-proto">Visual Comparison: <code>prototype</code> vs <code>__proto__</code></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766943710881/eb42bbde-b471-4709-b2a1-c87d1412a4b5.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-does-new-really-do">What Does <code>new</code> Really Do?</h2>
<p>The <code>new</code> keyword is like a house-building robot. Let's see what it does step by step:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Car</span>(<span class="hljs-params">brand, model</span>) </span>{
    <span class="hljs-built_in">this</span>.brand = brand;
    <span class="hljs-built_in">this</span>.model = model;
}

Car.prototype.drive = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span> is driving`</span>);
};

<span class="hljs-keyword">const</span> myCar = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>);
</code></pre>
<p>When you use <code>new Car("Toyota", "Camry")</code>, JavaScript does this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// What 'new' does behind the scenes:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">simulateNew</span>(<span class="hljs-params">Constructor, ...args</span>) </span>{
    <span class="hljs-comment">// 1. Create a new empty object</span>
    <span class="hljs-keyword">const</span> obj = {};

    <span class="hljs-comment">// 2. Set the object's __proto__ to Constructor.prototype</span>
    obj.__proto__ = Constructor.prototype;
    <span class="hljs-comment">// or: Object.setPrototypeOf(obj, Constructor.prototype);</span>

    <span class="hljs-comment">// 3. Execute the constructor with 'this' bound to the new object</span>
    <span class="hljs-keyword">const</span> result = Constructor.apply(obj, args);

    <span class="hljs-comment">// 4. Return the object (unless constructor returns its own object)</span>
    <span class="hljs-keyword">return</span> result <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Object</span> ? result : obj;
}

<span class="hljs-keyword">const</span> myCar2 = simulateNew(Car, <span class="hljs-string">"Honda"</span>, <span class="hljs-string">"Civic"</span>);
myCar2.drive(); <span class="hljs-comment">// "Honda Civic is driving"</span>
</code></pre>
<h2 id="heading-inheritance-without-extends-the-old-school-way">Inheritance Without <code>extends</code>: The Old-School Way</h2>
<p>Before ES6 classes, JavaScript developers achieved inheritance using prototypes directly. It's like creating a specialized blueprint that builds upon a general one.</p>
<h3 id="heading-method-1-using-objectcreate">Method 1: Using <code>Object.create()</code></h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Parent "class"</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Vehicle</span>(<span class="hljs-params">type</span>) </span>{
    <span class="hljs-built_in">this</span>.type = type;
    <span class="hljs-built_in">this</span>.speed = <span class="hljs-number">0</span>;
}

Vehicle.prototype.accelerate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">amount</span>) </span>{
    <span class="hljs-built_in">this</span>.speed += amount;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span> accelerating to <span class="hljs-subst">${<span class="hljs-built_in">this</span>.speed}</span> mph`</span>);
};

<span class="hljs-comment">// Child "class"</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Motorcycle</span>(<span class="hljs-params">type, brand</span>) </span>{
    <span class="hljs-comment">// Call parent constructor</span>
    Vehicle.call(<span class="hljs-built_in">this</span>, type);
    <span class="hljs-built_in">this</span>.brand = brand;
}

<span class="hljs-comment">// Set up inheritance - Create prototype chain</span>
Motorcycle.prototype = <span class="hljs-built_in">Object</span>.create(Vehicle.prototype);
Motorcycle.prototype.constructor = Motorcycle;

<span class="hljs-comment">// Add child-specific methods</span>
Motorcycle.prototype.wheelie = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span> doing a wheelie!`</span>);
};

<span class="hljs-keyword">const</span> myBike = <span class="hljs-keyword">new</span> Motorcycle(<span class="hljs-string">"Motorcycle"</span>, <span class="hljs-string">"Harley"</span>);
myBike.accelerate(<span class="hljs-number">50</span>); <span class="hljs-comment">// "Motorcycle accelerating to 50 mph"</span>
myBike.wheelie(); <span class="hljs-comment">// "Harley Motorcycle doing a wheelie!"</span>
</code></pre>
<h3 id="heading-method-2-manual-prototype-assignment">Method 2: Manual Prototype Assignment</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}

Animal.prototype.eat = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is eating`</span>);
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">name, breed</span>) </span>{
    Animal.call(<span class="hljs-built_in">this</span>, name);
    <span class="hljs-built_in">this</span>.breed = breed;
}

<span class="hljs-comment">// Create the inheritance link</span>
Dog.prototype = <span class="hljs-built_in">Object</span>.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> the <span class="hljs-subst">${<span class="hljs-built_in">this</span>.breed}</span> says Woof!`</span>);
};

<span class="hljs-keyword">const</span> buddy = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Buddy"</span>, <span class="hljs-string">"Golden Retriever"</span>);
buddy.eat();  <span class="hljs-comment">// "Buddy is eating" (inherited)</span>
buddy.bark(); <span class="hljs-comment">// "Buddy the Golden Retriever says Woof!"</span>
</code></pre>
<h3 id="heading-the-prototype-chain-visualization">The Prototype Chain Visualization</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766943961062/cc722379-fca8-49b4-8b01-de76b6d42f2a.jpeg" alt class="image--center mx-auto" /></p>
<h2 id="heading-events-in-javascript-the-party-invitation-analogy">Events in JavaScript: The Party Invitation Analogy</h2>
<p>JavaScript events are like sending party invitations through an apartment building. Let's understand this with a real-world analogy.</p>
<h3 id="heading-the-apartment-building-model">The Apartment Building Model</h3>
<p>Imagine an apartment building with floors and apartments:</p>
<ul>
<li><p><strong>Building</strong> = <code>&lt;html&gt;</code></p>
</li>
<li><p><strong>Floor</strong> = <code>&lt;body&gt;</code> or <code>&lt;div&gt;</code></p>
</li>
<li><p><strong>Apartment</strong> = <code>&lt;button&gt;</code> or <code>&lt;input&gt;</code></p>
</li>
</ul>
<p>When you knock on an apartment door (click a button), three things happen:</p>
<ol>
<li><p><strong>Capturing Phase</strong>: The sound travels DOWN from the building entrance to your apartment</p>
</li>
<li><p><strong>Target Phase</strong>: You answer the door</p>
</li>
<li><p><strong>Bubbling Phase</strong>: The sound travels UP back through the building</p>
</li>
</ol>
<h3 id="heading-event-propagation-code-example">Event Propagation Code Example</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// HTML structure (conceptually):</span>
<span class="hljs-comment">// &lt;div id="building"&gt;</span>
<span class="hljs-comment">//   &lt;div id="floor"&gt;</span>
<span class="hljs-comment">//     &lt;button id="apartment"&gt;Click Me&lt;/button&gt;</span>
<span class="hljs-comment">//   &lt;/div&gt;</span>
<span class="hljs-comment">// &lt;/div&gt;</span>

<span class="hljs-keyword">const</span> building = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'building'</span>);
<span class="hljs-keyword">const</span> floor = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'floor'</span>);
<span class="hljs-keyword">const</span> apartment = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'apartment'</span>);

<span class="hljs-comment">// CAPTURING PHASE (going down) - set third parameter to true</span>
building.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'1. Building heard the knock (capturing)'</span>);
}, <span class="hljs-literal">true</span>);

floor.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'2. Floor heard the knock (capturing)'</span>);
}, <span class="hljs-literal">true</span>);

<span class="hljs-comment">// TARGET PHASE</span>
apartment.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'3. Apartment answers! (target)'</span>);
    <span class="hljs-comment">// event.stopPropagation(); // Stop the sound from traveling</span>
});

<span class="hljs-comment">// BUBBLING PHASE (going up) - default behavior</span>
floor.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'4. Floor heard the answer (bubbling)'</span>);
});

building.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'5. Building heard the answer (bubbling)'</span>);
});

<span class="hljs-comment">// When you click the button, output:</span>
<span class="hljs-comment">// 1. Building heard the knock (capturing)</span>
<span class="hljs-comment">// 2. Floor heard the knock (capturing)</span>
<span class="hljs-comment">// 3. Apartment answers! (target)</span>
<span class="hljs-comment">// 4. Floor heard the answer (bubbling)</span>
<span class="hljs-comment">// 5. Building heard the answer (bubbling)</span>
</code></pre>
<h3 id="heading-event-delegation-the-receptionist-pattern">Event Delegation: The Receptionist Pattern</h3>
<p>Instead of hiring a receptionist for each apartment, hire ONE receptionist at the building entrance who handles all deliveries.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// BAD: Adding listener to each button (like hiring many receptionists)</span>
<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.apartment'</span>).forEach(<span class="hljs-function"><span class="hljs-params">button</span> =&gt;</span> {
    button.addEventListener(<span class="hljs-string">'click'</span>, handleClick);
});

<span class="hljs-comment">// GOOD: Event delegation (one receptionist for the building)</span>
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'building'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-keyword">if</span> (event.target.classList.contains(<span class="hljs-string">'apartment'</span>)) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Package delivered to apartment <span class="hljs-subst">${event.target.id}</span>`</span>);
    }
});
</code></pre>
<h3 id="heading-common-event-methods">Common Event Methods</h3>
<pre><code class="lang-javascript">element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-comment">// Stop bubbling up</span>
    event.stopPropagation();

    <span class="hljs-comment">// Prevent default behavior (like form submission)</span>
    event.preventDefault();

    <span class="hljs-comment">// Who was clicked?</span>
    <span class="hljs-built_in">console</span>.log(event.target);

    <span class="hljs-comment">// Who is listening?</span>
    <span class="hljs-built_in">console</span>.log(event.currentTarget);

    <span class="hljs-comment">// Where in the journey?</span>
    <span class="hljs-built_in">console</span>.log(event.eventPhase); <span class="hljs-comment">// 1=capturing, 2=target, 3=bubbling</span>
});
</code></pre>
<h2 id="heading-practical-example-building-a-shape-hierarchy">Practical Example: Building a Shape Hierarchy</h2>
<p>Let's combine everything we've learned into a practical example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Base Shape "class"</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Shape</span>(<span class="hljs-params">color</span>) </span>{
    <span class="hljs-built_in">this</span>.color = color;
}

Shape.prototype.describe = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A <span class="hljs-subst">${<span class="hljs-built_in">this</span>.color}</span> shape`</span>);
};

<span class="hljs-comment">// Circle inherits from Shape</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Circle</span>(<span class="hljs-params">color, radius</span>) </span>{
    Shape.call(<span class="hljs-built_in">this</span>, color); <span class="hljs-comment">// Inherit properties</span>
    <span class="hljs-built_in">this</span>.radius = radius;
}

Circle.prototype = <span class="hljs-built_in">Object</span>.create(Shape.prototype);
Circle.prototype.constructor = Circle;

Circle.prototype.area = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * <span class="hljs-built_in">this</span>.radius ** <span class="hljs-number">2</span>;
};

Circle.prototype.describe = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A <span class="hljs-subst">${<span class="hljs-built_in">this</span>.color}</span> circle with radius <span class="hljs-subst">${<span class="hljs-built_in">this</span>.radius}</span>`</span>);
};

<span class="hljs-comment">// Rectangle inherits from Shape</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Rectangle</span>(<span class="hljs-params">color, width, height</span>) </span>{
    Shape.call(<span class="hljs-built_in">this</span>, color);
    <span class="hljs-built_in">this</span>.width = width;
    <span class="hljs-built_in">this</span>.height = height;
}

Rectangle.prototype = <span class="hljs-built_in">Object</span>.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

Rectangle.prototype.area = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.width * <span class="hljs-built_in">this</span>.height;
};

Rectangle.prototype.describe = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A <span class="hljs-subst">${<span class="hljs-built_in">this</span>.color}</span> rectangle <span class="hljs-subst">${<span class="hljs-built_in">this</span>.width}</span>x<span class="hljs-subst">${<span class="hljs-built_in">this</span>.height}</span>`</span>);
};

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> circle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-string">"red"</span>, <span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> rectangle = <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-string">"blue"</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>);

circle.describe(); <span class="hljs-comment">// "A red circle with radius 5"</span>
<span class="hljs-built_in">console</span>.log(circle.area()); <span class="hljs-comment">// 78.54</span>

rectangle.describe(); <span class="hljs-comment">// "A blue rectangle 4x6"</span>
<span class="hljs-built_in">console</span>.log(rectangle.area()); <span class="hljs-comment">// 24</span>

<span class="hljs-comment">// Both are shapes!</span>
<span class="hljs-built_in">console</span>.log(circle <span class="hljs-keyword">instanceof</span> Circle);    <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(circle <span class="hljs-keyword">instanceof</span> Shape);     <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(rectangle <span class="hljs-keyword">instanceof</span> Shape);  <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ol>
<li><p><strong>Prototypes are blueprints</strong> - They define shared behavior for objects</p>
</li>
<li><p><code>prototype</code> is on constructors - The blueprint itself</p>
</li>
<li><p><code>__proto__</code> is on instances - The reference to the blueprint</p>
</li>
<li><p><code>new</code> creates and links - It builds the object and sets up the prototype chain</p>
</li>
<li><p><strong>Inheritance without</strong> <code>extends</code> - Use <code>Object.create()</code> and <code>.call()</code> for classical inheritance</p>
</li>
<li><p><strong>Events flow in three phases</strong> - Capturing → Target → Bubbling</p>
</li>
</ol>
<h2 id="heading-modern-javascript-note">Modern JavaScript Note</h2>
<p>While understanding prototypes is crucial, modern JavaScript (ES6+) provides the <code>class</code> syntax as syntactic sugar:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-keyword">constructor</span>(type) {
        <span class="hljs-built_in">this</span>.type = type;
    }

    accelerate() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.type}</span> is accelerating`</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Motorcycle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-keyword">constructor</span>(type, brand) {
        <span class="hljs-built_in">super</span>(type);
        <span class="hljs-built_in">this</span>.brand = brand;
    }

    wheelie() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> doing a wheelie!`</span>);
    }
}
</code></pre>
<p>Under the hood, this still uses prototypes! The <code>class</code> syntax just makes it cleaner and more familiar to developers from other languages.</p>
<hr />
<p><strong>Remember</strong>: JavaScript's prototype system is like genetic inheritance—objects inherit traits from their prototypes, creating a chain of shared behaviors that makes code efficient and elegant. Master this, and you'll truly understand JavaScript's object-oriented nature!</p>
<p>What aspect of prototypes or events would you like to explore deeper? Drop your questions in the comments below! 🚀</p>
]]></content:encoded></item></channel></rss>