<?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[PBlogs]]></title><description><![CDATA[PBlogs]]></description><link>https://pblogs.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 09 Jun 2026 14:53:12 GMT</lastBuildDate><atom:link href="https://pblogs.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[OOP in JavaScript]]></title><description><![CDATA[In this article, we will look at some Object Oriented Programming concepts like classes, objects, etc. Javascript doesn’t inherently support classes rather it uses a concept known as prototype. Let’s understand the prototypal behaviour of JS in depth...]]></description><link>https://pblogs.hashnode.dev/oop-in-javascript</link><guid isPermaLink="true">https://pblogs.hashnode.dev/oop-in-javascript</guid><category><![CDATA[property descriptor]]></category><category><![CDATA[oop]]></category><category><![CDATA[prototype]]></category><category><![CDATA[prototypal chaining]]></category><category><![CDATA[class]]></category><category><![CDATA[object]]></category><category><![CDATA[new keyword]]></category><category><![CDATA[constructor]]></category><category><![CDATA[getter and setter]]></category><category><![CDATA[static]]></category><category><![CDATA[private property]]></category><category><![CDATA[inheritance]]></category><category><![CDATA[encapsulation]]></category><category><![CDATA[polymorphism]]></category><category><![CDATA[abstraction]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Fri, 15 Aug 2025 06:33:09 GMT</pubDate><content:encoded><![CDATA[<p>In this article, we will look at some Object Oriented Programming concepts like classes, objects, etc. Javascript doesn’t inherently support classes rather it uses a concept known as prototype. Let’s understand the prototypal behaviour of JS in depth.</p>
<h2 id="heading-prototypal-behavior">Prototypal Behavior</h2>
<h3 id="heading-prototype">Prototype</h3>
<p>Prototype in JS are regular objects which consists of some properties which can be inherited by other objects. So, prototype can be seen as a blueprint which an object inherits.</p>
<ul>
<li><p>Every function has a property named “prototype” which defines a blueprint for objects created via it when used as a constructor. This is where all objects get their prototype from.</p>
</li>
<li><p>Every object has a property [[prototype]] (or__proto__) which contains the reference for the prototype it inherits. So, every object has __<strong>proto</strong>__ which points to prototype object, prototype being an object also has a __proto__ pointing to parent prototype and this continues till root prototype object which has __proto__ set to null. This is referred to as prototype chaining.</p>
</li>
<li><p>When object is created using a constructor function via new keyword, prototype of the function gets assigned to the __proto__ of newly created object.</p>
</li>
</ul>
<p>Summarizing above points, each object has __proto__ property. Function objects, in addition also contains a prototype property, so function objects have both protoype and __proto__. Objects are created using these constructor functions and while doing so, prototype of function is assigned to <strong>proto</strong> of object. So, prototypes originally generate from functions which are then assigned to objects. Root of all prototypes is Object prototype.</p>
<h3 id="heading-prototype-chaining">Prototype Chaining</h3>
<p>Each object has its own properties and a reference to its prototype(referenced by __<strong>proto__</strong>). Prototype in return being an object has its own __proto__ and this chain continues till the root object in which __<strong>proto__</strong> is set to null. So, JS first looks a value in object’s own set of properties, if not found, it then searches <strong>prototype</strong> of the object, if it still fails, it then searches in the next prototype in the chain until it finds the value or reaches null.</p>
<p>Let’s look at an example to understand prototypal behavior clearly,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"name"</span>
}

Person.prototype.greet = <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"</span>)
}

<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();
<span class="hljs-keyword">const</span> person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Demo"</span>);

<span class="hljs-comment">// obj and person get their __proto__ from respective cnstructors</span>
<span class="hljs-built_in">console</span>.log(obj.__proto__ === <span class="hljs-built_in">Object</span>.prototype) <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(person.__proto__ === Person.prototype) <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Each prototype object also has a __proto__ pointing to Object.prototype, unless modified</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.prototype.__proto__) <span class="hljs-comment">// null</span>
<span class="hljs-built_in">console</span>.log(Person.prototype.__proto__ === <span class="hljs-built_in">Object</span>.prototype) <span class="hljs-comment">// true</span>

<span class="hljs-comment">// As Object and Person are function objects (constructor), they get __proto__ from Function.prototype</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.__proto__ === <span class="hljs-built_in">Function</span>.prototype) <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(Person.__proto__ === <span class="hljs-built_in">Function</span>.prototype) <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Prototype chaining</span>
<span class="hljs-built_in">console</span>.log(person.name) <span class="hljs-comment">// own property</span>
person.greet() <span class="hljs-comment">// Available in person.__proto__ - Inherited from Person.prototype</span>
<span class="hljs-built_in">console</span>.log(person.toString()) <span class="hljs-comment">// Available in person.__proto__.__proto__ - Inherited from Object.prototype</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754988417064/f320b731-daee-4342-a6b8-2b6a731d85d3.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>If you create a object literal without using any constructor function, it is same as creating a new Obejct() or Object.create(Object.prototype). Newly created object literal has Object.prototype as its __proto__</p>
</blockquote>
<p>Now, let’s look how objects are created in prototypal aspect of Javascript:</p>
<ul>
<li><p>Define a constructor function</p>
</li>
<li><p>Assign properties using this keyword</p>
</li>
<li><p>Add functionalities in its prototype</p>
</li>
<li><p>Create objects using the new keyword.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, email</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.email = email;
}

Person.prototype.displayName = <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);
}

Person.prototype.displayEmail = <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>.email);
}

<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p1"</span>, <span class="hljs-string">"p1@test.com"</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p2"</span>, <span class="hljs-string">"p2@test.com"</span>);

p1.displayName(); <span class="hljs-comment">// p1</span>
p1.displayEmail(); <span class="hljs-comment">// p1@test.com</span>

p2.displayName(); <span class="hljs-comment">// p2</span>
p2.displayEmail(); <span class="hljs-comment">// p2@test.com</span>
</code></pre>
<h2 id="heading-class-es6">Class (ES6+)</h2>
<p>Classes are syntactic sugar build over prototypes. It provides clean structure for defining classes and instantiating objects from them. Let’s look at the class structure of above example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{

    <span class="hljs-keyword">constructor</span>(name, email) {
        <span class="hljs-built_in">this</span>.name = name;
        <span class="hljs-built_in">this</span>.email = email
    }

    displayName() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }

    displayEmail() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.email);
    }
}

<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p1"</span>, <span class="hljs-string">"p1@test.com"</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p2"</span>, <span class="hljs-string">"p2@test.com"</span>);

p1.displayName(); <span class="hljs-comment">// p1</span>
p1.displayEmail(); <span class="hljs-comment">// p1@test.com</span>

p2.displayName(); <span class="hljs-comment">// p2</span>
p2.displayEmail(); <span class="hljs-comment">// p2@test.com</span>
</code></pre>
<p>It internally creates a Person constructor function, adds defined methods in its prototype.</p>
<h2 id="heading-object-oriented-programming-concepts">Object Oriented Programming Concepts</h2>
<h3 id="heading-new-keyword">NEW Keyword</h3>
<p><em>new</em> keyword is used with constructor function to create a new object and bind it with the function call. It does the following:</p>
<ul>
<li><p>Creates a new object.</p>
</li>
<li><p>Assigns __proto__ from constructors prototype.</p>
</li>
<li><p>Binds the object with function call using this.</p>
</li>
<li><p>Executes the constructor on newly created object and returns the object.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}

Person.prototype.greet = <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 <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
}

<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p1"</span>);
p1.greet(); <span class="hljs-comment">// Hello p1</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755003573997/27b2eaeb-3812-4f4b-ac8b-4b94aee7c94d.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-constructor">Constructor</h3>
<p>Constructor is a method used to initialize an object. It assigns all the initial properties to newly created object. Just like regular functions, it also has access to this keyword which holds reference to the current object. After initialization, it returns the newly created object.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ------------------- PROTOTYPE Based</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}
<span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p1"</span>);

<span class="hljs-comment">// ------------------- CLASS Based</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> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"p1"</span>);
</code></pre>
<h3 id="heading-getters-and-setters">Getters and Setters</h3>
<p>Getters and setters are methods used to get value of a property or set a value.</p>
<ul>
<li><p>Each property has internal getters and setters whcih can be overriden using get or set keywords.</p>
</li>
<li><p>When a property is accessed using dot(.) operator, getter is called, while when a property is assigned a value using dot(.) operator, setter is called.</p>
</li>
<li><p>Getters can be used to return formatted values while setters can be used to store values after proper checks and sanitizations.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// ------------------- PROTOTYPE Based</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">const</span> parts = name.split(<span class="hljs-string">" "</span>);
    <span class="hljs-built_in">this</span>.firstName = parts[<span class="hljs-number">0</span>];
    <span class="hljs-built_in">this</span>.lastName = parts[<span class="hljs-number">1</span>] || <span class="hljs-string">""</span>;
}

<span class="hljs-built_in">Object</span>.defineProperty(Person.prototype, <span class="hljs-string">"name"</span>, {
    <span class="hljs-attr">get</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>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName;
    },
    <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{
        <span class="hljs-keyword">const</span> parts = name.split(<span class="hljs-string">" "</span>);
        <span class="hljs-built_in">this</span>.firstName = parts[<span class="hljs-number">0</span>];
        <span class="hljs-built_in">this</span>.lastName = parts[<span class="hljs-number">1</span>] || <span class="hljs-string">""</span>;
    }
});

<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Test User"</span>);
<span class="hljs-built_in">console</span>.log(p.firstName) <span class="hljs-comment">// Test</span>
<span class="hljs-built_in">console</span>.log(p.lastName) <span class="hljs-comment">// User</span>
<span class="hljs-built_in">console</span>.log(p.name) <span class="hljs-comment">// Test User</span>

p.name = <span class="hljs-string">"Demo User"</span>;
<span class="hljs-built_in">console</span>.log(p.name); <span class="hljs-comment">// Demo User</span>

<span class="hljs-comment">// ------------------- CLASS Based</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-keyword">const</span> parts = name.split(<span class="hljs-string">" "</span>);
        <span class="hljs-built_in">this</span>.firstName = parts[<span class="hljs-number">0</span>];
        <span class="hljs-built_in">this</span>.lastName = parts[<span class="hljs-number">1</span>] || <span class="hljs-string">""</span>;
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName;
    }

    <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">name</span>) {
        <span class="hljs-keyword">const</span> parts = name.split(<span class="hljs-string">" "</span>);
        <span class="hljs-built_in">this</span>.firstName = parts[<span class="hljs-number">0</span>];
        <span class="hljs-built_in">this</span>.lastName = parts[<span class="hljs-number">1</span>] || <span class="hljs-string">""</span>;
    }

}

<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Test User"</span>);
<span class="hljs-built_in">console</span>.log(p.firstName) <span class="hljs-comment">// Test</span>
<span class="hljs-built_in">console</span>.log(p.lastName) <span class="hljs-comment">// User</span>
<span class="hljs-built_in">console</span>.log(p.name) <span class="hljs-comment">// Test User</span>

p.name = <span class="hljs-string">"Demo User"</span>;
<span class="hljs-built_in">console</span>.log(p.name); <span class="hljs-comment">// Demo User</span>
</code></pre>
<h3 id="heading-static-properties">Static Properties</h3>
<p>Static properties are directly defined on constructor function and can be accessed on constructor or the class level. These properties doesn’t exist on the instance level.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ------------------- PROTOTYPE Based</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
}

Person.prototype.a = <span class="hljs-number">10</span>; <span class="hljs-comment">// can be accessed at instance level</span>
Person.b = <span class="hljs-number">20</span>; <span class="hljs-comment">// can't be accessed via instance</span>

<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Test"</span>);
<span class="hljs-built_in">console</span>.log(p.a); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(p.b); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(Person.b); <span class="hljs-comment">// 20</span>

<span class="hljs-comment">// ------------------- CLASS Based</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{

    <span class="hljs-keyword">static</span> a = <span class="hljs-number">10</span>;

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.name = name;
    }

    <span class="hljs-keyword">static</span> greet() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
    }
}

<span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Test"</span>);
<span class="hljs-built_in">console</span>.log(p.a); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(Person.a); <span class="hljs-comment">// 10</span>
p.greet() <span class="hljs-comment">// p.greet is not a function</span>
Person.greet(); <span class="hljs-comment">// Hello</span>
</code></pre>
<h3 id="heading-private-properties">Private Properties</h3>
<p>Sometimes, properties of an instance needs to be hidden to keep internal implementations safe. These properties should not be accessible or modified outside the class. There are various ways adopted to make properties of an object private, let’s look at them one by one:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{

    _secret; 

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>._secret = name + <span class="hljs-string">"secret"</span>;
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._secret.slice(<span class="hljs-number">0</span>, <span class="hljs-built_in">this</span>._secret.length<span class="hljs-number">-6</span>);
    }

    <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">name</span>) {
        <span class="hljs-built_in">this</span>._secret = name + <span class="hljs-string">"secret"</span>;
    }

}

<span class="hljs-keyword">const</span> test = <span class="hljs-keyword">new</span> Test(<span class="hljs-string">"Test"</span>);
test.name = <span class="hljs-string">"abc"</span>;  
<span class="hljs-built_in">console</span>.log(test.name) <span class="hljs-comment">// abc</span>

<span class="hljs-built_in">console</span>.log(test._secret) <span class="hljs-comment">// abcsecret -- PROBLEM</span>
</code></pre>
<p>In above example, though we haven’t exposed the internal property - _secret, it can still be accessed as it is an instance property, therefore it is not truly private.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {

        <span class="hljs-keyword">let</span> _secret = name + <span class="hljs-string">"secret"</span>;

        <span class="hljs-built_in">this</span>.getName = <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-keyword">return</span> _secret.slice(<span class="hljs-number">0</span>, _secret.length<span class="hljs-number">-6</span>);
        }

        <span class="hljs-built_in">this</span>.setName = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
            _secret = name + <span class="hljs-string">"secret"</span>;
        }
    }

}

<span class="hljs-keyword">const</span> test = <span class="hljs-keyword">new</span> Test(<span class="hljs-string">"Test"</span>);
test.setName(<span class="hljs-string">"abc"</span>);  
<span class="hljs-built_in">console</span>.log(test.getName()) <span class="hljs-comment">// abc</span>
</code></pre>
<p>In above example, closure is used to define an internal property which can be accessed by getters and setters but not as an instance property, therefore it is truly private. But each instance will get it’s own copy of getters and setters, so it is not memory efficient.</p>
<p>Given below is the modern and clean way of defining private properties in a class -</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{

    #secret;

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.#secret = name + <span class="hljs-string">"secret"</span>;
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#secret.slice(<span class="hljs-number">0</span>, <span class="hljs-built_in">this</span>.#secret.length - <span class="hljs-number">6</span>);
    }

    <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">name</span>) {
        <span class="hljs-built_in">this</span>.#secret = name + <span class="hljs-string">"secret"</span>;
    }

}

<span class="hljs-keyword">const</span> test = <span class="hljs-keyword">new</span> Test(<span class="hljs-string">"Test"</span>);
test.name = <span class="hljs-string">"abc"</span>; 
<span class="hljs-built_in">console</span>.log(test.name) <span class="hljs-comment">// abc</span>
<span class="hljs-built_in">console</span>.log(test.#secret) <span class="hljs-comment">// Private field '#secret' must be declared in an enclosing class</span>
</code></pre>
<p>When # is used with a property it is reserved as private slot internally and can’t be accessed outside the class.</p>
<p>Similary, methods or static propeties can also be made private -</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{

    #secret;
    <span class="hljs-keyword">static</span> #staticSecret = <span class="hljs-string">'staticSecret'</span>;

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.#secret = name + <span class="hljs-string">"secret"</span>;
    }

    #extractName() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#secret.slice(<span class="hljs-number">0</span>, <span class="hljs-built_in">this</span>.#secret.length - <span class="hljs-number">6</span>);
    }

    <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#extractName();
    }

    <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">name</span>) {
        <span class="hljs-built_in">this</span>.#secret = name + <span class="hljs-string">"secret"</span>;
    }

}

<span class="hljs-keyword">const</span> test = <span class="hljs-keyword">new</span> Test(<span class="hljs-string">"Test"</span>);
test.name = <span class="hljs-string">"abc"</span>;
<span class="hljs-built_in">console</span>.log(test.name);
<span class="hljs-built_in">console</span>.log(test.#extractName()) <span class="hljs-comment">// error</span>
<span class="hljs-built_in">console</span>.log(Test.#staticSecret) <span class="hljs-comment">// error</span>
</code></pre>
<h3 id="heading-property-descriptors">Property Descriptors</h3>
<p>Property decriptors are the objects used to configure instance properties. They can used to configure following values -</p>
<ul>
<li><p>Value of the property</p>
</li>
<li><p>Read only or Writable</p>
</li>
<li><p>Enumerable (in loops)</p>
</li>
<li><p>Configurable (can be deleted or re-configured)</p>
</li>
<li><p>Getters and Setters</p>
</li>
</ul>
<p>Every property has a property descriptor set for it. By default, following values are set internally -</p>
<ul>
<li><p>writable: true</p>
</li>
<li><p>enumerable: true</p>
</li>
<li><p>configurable: true</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">a</span>: <span class="hljs-number">10</span>
};
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"name"</span>, {
    <span class="hljs-attr">value</span>: <span class="hljs-string">"Test"</span>,
    <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,
});

<span class="hljs-comment">// NOT WRITABLE</span>
obj.name = <span class="hljs-string">"Demo"</span>;
<span class="hljs-built_in">console</span>.log(obj.name) <span class="hljs-comment">// Test</span>

<span class="hljs-comment">// NOT ENUMERABLE</span>
<span class="hljs-built_in">console</span>.log(obj) <span class="hljs-comment">//{a: 10, name: 'Test'}</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> obj) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span> =&gt; <span class="hljs-subst">${obj[key]}</span>`</span>)
}
<span class="hljs-comment">// a =&gt; 10</span>

<span class="hljs-comment">// NOT CONFIGURABLE </span>
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"name"</span>, {
    <span class="hljs-attr">value</span>: <span class="hljs-string">"Test"</span>,
    <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,
});
<span class="hljs-comment">// Cannot redefine property: name</span>
</code></pre>
<p>These properties can be used to define constants or stop iteration over a property. Similary, getters and setters can be defined -</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">a</span>: <span class="hljs-number">10</span>
};
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"name"</span>, {
    <span class="hljs-attr">value</span>: <span class="hljs-string">"Test"</span>, <span class="hljs-comment">// Invalid property descriptor. Cannot both specify accessors and a value or writable attribute</span>
    <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// Invalid property descriptor. Cannot both specify accessors and a value or writable attribute</span>
    <span class="hljs-attr">get</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.name + <span class="hljs-string">"abc"</span>,
    <span class="hljs-attr">set</span>: <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-built_in">this</span>.name = name.toUpperCase()
});

obj.name = <span class="hljs-string">"Test"</span>;
<span class="hljs-built_in">console</span>.log(obj.name); <span class="hljs-comment">// TESTabc</span>
</code></pre>
<blockquote>
<p>value and writable properties are not accepted if getters and setters are provided.</p>
<p>getOwnPropertyDescriptor() can be used to view property decriptor for an instance property.</p>
</blockquote>
<p>You can define property descriptors in classes and constructor functions similarly as we did for object literals -</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ------------------- PROTOTYPE Based</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">Object</span>.defineProperty(<span class="hljs-built_in">this</span>, <span class="hljs-string">"name"</span>, {
    <span class="hljs-attr">value</span>: name,
    <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>
  });
}

<span class="hljs-comment">// ------------------- CLASS Based</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">Object</span>.defineProperty(<span class="hljs-built_in">this</span>, <span class="hljs-string">"name"</span>, {
      <span class="hljs-attr">value</span>: name,
      <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>
    });
  }
}
</code></pre>
<h3 id="heading-inheritance">Inheritance</h3>
<p>Inheritance is an OOP concept in which child instance can inherit parent properties. In Javascript, it is implemented using prototype chaining. Let’s look at some examples to understand:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ------------------- PROTOTYPE Based</span>
<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.displayName = <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);
}

<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;
}
Dog.prototype = <span class="hljs-built_in">Object</span>.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.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> barks...`</span>);
}

<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Bruno"</span>, <span class="hljs-string">"Beagle"</span>);
dog.displayName(); <span class="hljs-comment">// Bruno</span>
dog.speak(); <span class="hljs-comment">// Bruno barks...</span>

<span class="hljs-comment">// ------------------- CLASS Based</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.name = name;
    }
    displayName() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">constructor</span>(name, breed) {
        <span class="hljs-built_in">super</span>(name);
        <span class="hljs-built_in">this</span>.breed = breed;
    }
    speak() {
        <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> barks...`</span>);
    }
}

<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Bruno"</span>, <span class="hljs-string">"Beagle"</span>);
dog.displayName(); <span class="hljs-comment">// Bruno</span>
dog.speak(); <span class="hljs-comment">// Bruno barks...</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755090189978/e4d6807a-16ca-4e81-a23f-1b227820af27.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-encapsulation">Encapsulation</h3>
<p>Encapsulation is an OOP concept in which data(properties) and methods(functions) are wrapped up as single unit with proper access control. It involves hiding internal properties and exposing only the required ones, reffered to as data hiding.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  #password; <span class="hljs-comment">// private field</span>

  <span class="hljs-keyword">constructor</span>(username, password) {
    <span class="hljs-built_in">this</span>.username = username;
    <span class="hljs-built_in">this</span>.#password = password; 
  }

  getPassword() { 
    <span class="hljs-keyword">return</span> <span class="hljs-string">"****"</span>; <span class="hljs-comment">// controlled access</span>
  }

  setPassword(newPassword) {
    <span class="hljs-keyword">if</span> (newPassword.length &gt; <span class="hljs-number">5</span>) {
      <span class="hljs-built_in">this</span>.#password = newPassword;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Password too short!"</span>);
    }
  }
}

<span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Test"</span>, <span class="hljs-string">"secret123"</span>);
<span class="hljs-built_in">console</span>.log(u.username); <span class="hljs-comment">// Test</span>
<span class="hljs-built_in">console</span>.log(u.getPassword()); <span class="hljs-comment">// ****</span>
u.setPassword(<span class="hljs-string">"abc"</span>); <span class="hljs-comment">// Password too short!</span>
</code></pre>
<h3 id="heading-polymorphism">Polymorphism</h3>
<p>Polymorphism is an OOP concept in which a single method can have different behaviors based on how it is called. Method overriding is used to implement this concept.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Animal makes a sound"</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Dog barks"</span>);
  }
}

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> Animal();
<span class="hljs-keyword">const</span> d = <span class="hljs-keyword">new</span> Dog();
a.speak(); <span class="hljs-comment">// Animal makes a sound</span>
d.speak(); <span class="hljs-comment">// Dog barks</span>
</code></pre>
<h3 id="heading-abstraction">Abstraction</h3>
<p>Abstraction is an OOP concept in which internal implementation details are hidden exposing only the required functionalities. This way user can control state and behavior of an object by creating instances and executing methods on them without actually worrying about the internal details. In built functions like toString(), array methods - map, filter, etc. are good examples of abstraction.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering this in JavaScript]]></title><description><![CDATA[A function mainly has two requirements to run - it’s lexical environment which holds all the parameters and variables present in the function and the object on which the function gets executed, which is what is referenced by this keyword. Both lexica...]]></description><link>https://pblogs.hashnode.dev/mastering-this-in-javascript</link><guid isPermaLink="true">https://pblogs.hashnode.dev/mastering-this-in-javascript</guid><category><![CDATA[this keyword]]></category><category><![CDATA[Bind]]></category><category><![CDATA[call]]></category><category><![CDATA[apply]]></category><category><![CDATA[bindings]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Mon, 04 Aug 2025 17:32:43 GMT</pubDate><content:encoded><![CDATA[<p>A function mainly has two requirements to run - it’s lexical environment which holds all the parameters and variables present in the function and the object on which the function gets executed, which is what is referenced by <em>this</em> keyword. Both lexical environment and the <em>this</em> reference is contained in the execution context of a function which helps it in executing the code.</p>
<p>Regular functions often doesn’t require an object to execute on, they can sufficiently run on the passed parameters, but class methods usually require an object to perform the operations on and modify its state.</p>
<p>Let’s understand this with some examples:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">const</span> sum = a + b;
    <span class="hljs-keyword">return</span> sum;
}

<span class="hljs-keyword">const</span> result = sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(result);
<span class="hljs-comment">// Output: 3</span>
</code></pre>
<p>Above example defines a simple utility function which calculates the sum of 2 numbers passed to it. It operates on these parameters and produces the result.</p>
<pre><code class="lang-javascript"><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>, <span class="hljs-built_in">this</span>.name);
    }
}

<span class="hljs-keyword">const</span> user1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"User1"</span>);
<span class="hljs-keyword">const</span> user2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"User2"</span>);

user1.greet();
user2.greet();

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Hello,  User1</span>
<span class="hljs-comment">// Hello,  User2</span>
</code></pre>
<p>Above code snippet defines a constructor and greet function both of which requires an object to execute on. This object is provided to the function dynamically during runtime which is known as <em>this binding</em>. Whichever object the function is called with, becomes <em>this</em> for that particular function call. Each function owns a stack frame - execution context - which holds the <em>this</em> reference for the function. This is how multiple objects share the same function.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754069881439/d8d590bc-292e-4bb2-876d-8df558581373.png" alt class="image--center mx-auto" /></p>
<p>Now that we know what <em>this</em> keyword and <em>this binding</em> is, let’s look at how binding is done. We know object is binded to a function call dynamically when function begins its execution but how does JS engine decide which object to bind, in short how does this gets assigned for various function calls? Well, that depends on how the function is called. Let’s take a look at at them one by one.</p>
<ul>
<li><p>Default binding: When a regular function call is made, it gets binded to the global object for non-strict mode and undefined for strict mode, which basically makes sense as these functions are not intended to operate on any object.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span> === globalThis);
  }
  f();
  <span class="hljs-comment">// Output: true</span>

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-meta">      "use strict"</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  }
  f();
  <span class="hljs-comment">// Output: undefined</span>
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754071979848/f58bdb93-c909-4430-ad4d-c1ee5f91c661.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Implicit binding: When a function is called with an object using the (.) operator, it gets binded to that particular object.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayName</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  }

  <span class="hljs-keyword">const</span> obj = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"Demo"</span>
  }
  obj.displayName = displayName;
  obj.displayName();

  <span class="hljs-comment">// Output: Demo</span>
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754072600044/56f9171a-9383-47fb-b323-a7e5f0d3971c.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>New binding: When constructor functions are called with new keyword, it creates a new object and binds them together.</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
      <span class="hljs-built_in">this</span>.name = name
  }

  Person.prototype.displayName = <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);
  }

  <span class="hljs-keyword">const</span> obj1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Demo1"</span>);
  obj1.displayName();

  <span class="hljs-keyword">const</span> obj2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Demo2"</span>);
  obj2.displayName();

  <span class="hljs-comment">// Output:</span>
  <span class="hljs-comment">// Demo1</span>
  <span class="hljs-comment">// Demo2</span>
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754075562198/bfffe1e5-e7fa-4acc-9102-d335f2029874.png" alt class="image--center mx-auto" /></p>
<p>  For simplicity, lexical environments are omitted from the diagram but they hold reference to variables and functions present inside global and local scopes like <em>Person, obj1, ob2, etc</em>.</p>
</li>
<li><p>Explicit binding: Explicit binding can be used when you want to specify an object for binding yourself rather than relying on the implicit binding. JS provides 3 functions to do so:</p>
</li>
</ul>
<blockquote>
<p>Dot (.) operator also provides you the control to bind object to a function call but works only if the function is a property of the obejct(or present in its prototype chain).</p>
</blockquote>
<ol>
<li><p>call(): It is used to call a function on a given object which is passed as a parameter to the function. It takes first parameter as the object reference to which it needs to be binded, rest are the parameters to execute the function. Let’s look at an example to understand:</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setName</span>(<span class="hljs-params">name</span>) </span>{
     <span class="hljs-built_in">this</span>.name = name;
 }

 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, email</span>) </span>{
     setName(name);
     <span class="hljs-built_in">this</span>.email = email;
 }

 <span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Demo"</span>, <span class="hljs-string">"demo@demo.com"</span>);
 <span class="hljs-built_in">console</span>.log(p1);
 <span class="hljs-built_in">console</span>.log(globalThis.name);

 <span class="hljs-comment">// Output: </span>
 <span class="hljs-comment">// Person { email: 'demo@demo.com' }</span>
 <span class="hljs-comment">// Demo</span>
</code></pre>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754283633879/3740fcf7-8dd0-46ff-98b3-3f084ac20415.png" alt class="image--center mx-auto" /></p>
<p> In above example, <em>this</em> inside Person points to the newly created obejct p1 as we learned in the new binding, so email is set correctly in the p1 object. But setName didn’t set the name in the p1 object as it is a regular call so <em>this</em> in setName points to the global obejct. So, how do we get access to the outer this object inside setName? One possible way is to use the Dot operator(this.setName()), but setName isn’t a peoperty of p1 object. This is where call() is used, when you want to outsource some functionality to another function which is not part of the current object but you want it to run on the same object without creating a new one or executing it on global.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setName</span>(<span class="hljs-params">name</span>) </span>{
     <span class="hljs-built_in">this</span>.name = name;
 }

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

 <span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Demo"</span>, <span class="hljs-string">"demo@demo.com"</span>);
 <span class="hljs-built_in">console</span>.log(p1);

 <span class="hljs-comment">// Output: Person { name: 'Demo', email: 'demo@demo.com' }</span>
</code></pre>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754283762903/2a11f672-4b68-4bc4-8224-acbaddff1191.png" alt class="image--center mx-auto" /></p>
<p> Another example to understand it better:</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setName</span>(<span class="hljs-params">name</span>) </span>{
     <span class="hljs-built_in">this</span>.name = name;
 }

 <span class="hljs-keyword">const</span> p1 = {};
 setName.call(p1, <span class="hljs-string">"Demo"</span>); 
 <span class="hljs-comment">// We can't do setName("Demo") as it will execute on global object</span>
 <span class="hljs-comment">// We can't do p1.setName("Demo") as setName is not available on p1</span>
 <span class="hljs-built_in">console</span>.log(p1);

 <span class="hljs-comment">// Output: { name: 'Demo' }</span>
</code></pre>
</li>
<li><p>apply(): It does the same as call() except that it takes second argument as an array of parameters.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setName</span>(<span class="hljs-params">name, email</span>) </span>{
     <span class="hljs-built_in">this</span>.name = name;
     <span class="hljs-built_in">this</span>.email = email;
 }

 <span class="hljs-keyword">const</span> p1 = {};
 setName.apply(p1, [<span class="hljs-string">"Demo"</span>, <span class="hljs-string">"demo@demo.com"</span>]);
 <span class="hljs-built_in">console</span>.log(p1);

 <span class="hljs-comment">// Output: { name: 'Demo', email: 'demo@demo.com' }</span>
</code></pre>
</li>
<li><p>bind(): It returns a function binded with the passed object reference. So, whenever the function is called, it runs on that particular object irrespective of how it’s called.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setName</span>(<span class="hljs-params">name</span>) </span>{
     <span class="hljs-built_in">this</span>.name = name;
 }

 <span class="hljs-keyword">const</span> p1 = {};
 <span class="hljs-keyword">const</span> bindedSetName = setName.bind(p1);

 <span class="hljs-keyword">const</span> p2 = {};
 bindedSetName.call(p2, <span class="hljs-string">"Demo"</span>);

 <span class="hljs-built_in">console</span>.log(p1);
 <span class="hljs-built_in">console</span>.log(p2);

 <span class="hljs-comment">// Output:</span>
 <span class="hljs-comment">// { name: 'Demo' }</span>
 <span class="hljs-comment">// {}</span>
</code></pre>
<p> This is mainly used for callbacks where function call is made by JS and you do not control how it is called and which binding it uses, so it’s better to bind it beforehand.</p>
<pre><code class="lang-javascript"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> </span>{

     <span class="hljs-keyword">constructor</span>(label) {
         <span class="hljs-built_in">this</span>.label = label;
     }

     handleClick() {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.label);
     }
 }

 <span class="hljs-keyword">const</span> btn = <span class="hljs-keyword">new</span> Button(<span class="hljs-string">'Click me'</span>);
 <span class="hljs-built_in">setTimeout</span>(btn.handleClick, <span class="hljs-number">1000</span>); 

 <span class="hljs-comment">// Output: undefined</span>
</code></pre>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754286051959/7e3bf6a9-28d1-4a58-87b8-8c80fa50146e.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> </span>{

     <span class="hljs-keyword">constructor</span>(label) {
         <span class="hljs-built_in">this</span>.label = label;
         <span class="hljs-built_in">this</span>.handleClick = <span class="hljs-built_in">this</span>.handleClick.bind(<span class="hljs-built_in">this</span>);
     }

     handleClick() {
         <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.label);
     }
 }

 <span class="hljs-keyword">const</span> btn = <span class="hljs-keyword">new</span> Button(<span class="hljs-string">'Click me'</span>);
 <span class="hljs-built_in">setTimeout</span>(btn.handleClick, <span class="hljs-number">1000</span>); 

 <span class="hljs-comment">// Output: Click me</span>
</code></pre>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754286388519/ad72adb8-911a-4fb7-869b-c50dc67c2c03.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<blockquote>
<p>Callbacks passes in event listeners gets binded to target obejct, while setTimeout gets binded to global(non-strict) or undefined(strict) or timeout object(Node env). To override this default behaviour, use bind().</p>
<p>Both call() and apply() are used for runtime binding while bind() is used during creation phase binding. bind() basically captures this reference in closure of the function it returns. So, whenever the function runs, this is taken from the closure and doesn’t depend on how the function is called. This concept is used in arrow functions implicitly which we will learn in later sections.</p>
</blockquote>
<ul>
<li><p>Arrow function binding: Arrow functions always gets binded to their outer environment irrespective of how they are called. They capture this reference from the time of definition. Therefore, they can’t be binded explicitly so call(), apply() and bind() doesn’t work on arrow functions. In fact, it tends to solve most of the above problems without the need of explicit binding, especially, in case of callbacks.</p>
<pre><code class="lang-javascript">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> </span>{

      <span class="hljs-keyword">constructor</span>(label) {
          <span class="hljs-built_in">this</span>.label = label;
      }

      handleClick = <span class="hljs-function">() =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.label);
      }
  }

  <span class="hljs-keyword">const</span> btn = <span class="hljs-keyword">new</span> Button(<span class="hljs-string">'Click me'</span>);
  <span class="hljs-built_in">setTimeout</span>(btn.handleClick, <span class="hljs-number">1000</span>);

  <span class="hljs-comment">// Output: Click me</span>
</code></pre>
</li>
</ul>
<blockquote>
<p>But beware of this approach as arrow functions will add an instance property in the object and not on the prototype. Use it only when you can’t control how the function is called and you want to bind it to the outer scope like callbacks.</p>
</blockquote>
<ul>
<li><p>Super binding: In case of derived classes, it is necessary to call super constructor inside the derived class constructor before using this, so that super class properties can be set on the current object. Note that, when a method call is made using super, it binds the method with surrounding environment.</p>
<pre><code class="lang-javascript">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> </span>{

      <span class="hljs-keyword">constructor</span>(type = "parent") {
          <span class="hljs-built_in">this</span>.type = type;
      }

      display() {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
      }
  }

  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Parent</span> </span>{

      <span class="hljs-keyword">constructor</span>(name) {
          <span class="hljs-built_in">super</span>(<span class="hljs-string">"child"</span>);
          <span class="hljs-built_in">this</span>.name = name;
      }

      display() {
          <span class="hljs-built_in">super</span>.display();
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
      }
  }

  <span class="hljs-keyword">const</span> child = <span class="hljs-keyword">new</span> Child(<span class="hljs-string">"Demo"</span>);
  child.display();

  <span class="hljs-keyword">const</span> parent = <span class="hljs-keyword">new</span> Parent();
  parent.display();

  <span class="hljs-comment">/* Output
  Child { type: 'child', name: 'Demo' }
  Child { type: 'child', name: 'Demo' }
  Parent { type: 'parent' }
  */</span>
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754327911972/8dc595a6-7b94-425c-8b69-144be103b372.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Static methods binding: In case of static methods, this refers to the class object.</p>
<pre><code class="lang-javascript">  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> </span>{

      <span class="hljs-keyword">constructor</span>(type = "parent") {
          <span class="hljs-built_in">this</span>.type = type;
      }

      display() {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
      }

      <span class="hljs-keyword">static</span> f() {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
      }
  }

  <span class="hljs-keyword">const</span> parent = <span class="hljs-keyword">new</span> Parent();
  parent.f() <span class="hljs-comment">// parent.f is not a function</span>
  Parent.f() <span class="hljs-comment">// [class Parent]</span>
</code></pre>
</li>
</ul>
<blockquote>
<p>this can hold a object reference as well as primitive in case of strict mode, for non-strict mode, it gets wrapped with the Wrapper class object of primitive.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[JavaScript Function Cheatsheet]]></title><description><![CDATA[Javascript allows to declare functions in various ways. This article provides a quick overview of each type.

Simple function definition
 function hello() {
     console.log("hello")
 }
 hello();
 // Output: hello


Anonymous function expression
 con...]]></description><link>https://pblogs.hashnode.dev/javascript-function-cheatsheet</link><guid isPermaLink="true">https://pblogs.hashnode.dev/javascript-function-cheatsheet</guid><category><![CDATA[functions]]></category><category><![CDATA[anonymous function]]></category><category><![CDATA[named function expression]]></category><category><![CDATA[ Arrow Functions In JavaScript]]></category><category><![CDATA[callback]]></category><category><![CDATA[IIFE]]></category><category><![CDATA[default parameter]]></category><category><![CDATA[Arguments]]></category><category><![CDATA[arguments-object]]></category><category><![CDATA[rest parameter]]></category><category><![CDATA[HOF]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Wed, 30 Jul 2025 06:02:00 GMT</pubDate><content:encoded><![CDATA[<p>Javascript allows to declare functions in various ways. This article provides a quick overview of each type.</p>
<ol>
<li><p>Simple function definition</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
 }
 hello();
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Anonymous function expression</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> hello = <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"</span>)
 }
 hello();
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Named function expression</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> hello = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello1</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
 }
 hello()
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Arrow function (always anonymous)</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> hello = <span class="hljs-function">()  =&gt;</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
 }
 hello();
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Single line arrow function</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> hello = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
 hello();
 <span class="hljs-comment">// Output: hello</span>

 <span class="hljs-keyword">const</span> hello = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">"hello"</span>
 <span class="hljs-built_in">console</span>.log(hello());
 <span class="hljs-comment">// Output: hello</span>

 <span class="hljs-keyword">const</span> obj = <span class="hljs-function">() =&gt;</span> {<span class="hljs-attr">a</span>: <span class="hljs-string">"1"</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">"2"</span>} <span class="hljs-comment">// Error</span>
 <span class="hljs-keyword">const</span> obj = <span class="hljs-function">() =&gt;</span> ({<span class="hljs-attr">a</span>: <span class="hljs-string">"1"</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">"2"</span>}) <span class="hljs-comment">// Returns object</span>
</code></pre>
</li>
<li><p>Anonymous callback</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">setTimeout</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">"hello"</span>);
 })
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Named callback</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>);
 })
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Arrow function callback</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
 })
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>IIFE(Immediately Invoked Function Expression)</p>
<pre><code class="lang-javascript"> (
     <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"</span>)
     }
 )();
 <span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Named IIFE</p>
<pre><code class="lang-javascript">(
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
    }
)();
<span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Arrow function IIFE</p>
<pre><code class="lang-javascript">(
    <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
    }
)();
<span class="hljs-comment">// Output: hello</span>
</code></pre>
</li>
<li><p>Default parameters function</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name = <span class="hljs-string">"User"</span></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello, "</span>, name)
}
hello()
hello(<span class="hljs-string">"Demo User"</span>)
<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// hello,  User</span>
<span class="hljs-comment">// hello,  Demo User</span>
</code></pre>
</li>
<li><p>Arguments Object (Only in non-arrow functions)</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-built_in">arguments</span>.length;i++) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>[i])
    }
}
hello(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-string">"Demo"</span>);
<span class="hljs-comment">/* Output:
1
2
3
Demo
*/</span>
</code></pre>
</li>
<li><p>Rest parameters (At the end of parameters list, included in arguments object)</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params">name, ...params</span>) </span>{
    <span class="hljs-built_in">console</span>.log(name);
    params.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(item))
}
hello(<span class="hljs-string">"Demo"</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-comment">/* Output:
Demo
1
2
3
*/</span>
</code></pre>
<ol start="15">
<li><p>Higher-Order Functions (HOF)</p>
<ul>
<li><p>Either takes function as argument</p>
</li>
<li><p>or returns function as result</p>
</li>
<li><p>Inbulit HOFs: map, reduce, filter, etc.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">name</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Demo"</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">callback</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>, callback());
    }

    greet(name);

    <span class="hljs-comment">// Output: Hello Demo</span>

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello"</span>)
        }
    }
    <span class="hljs-comment">// const outer = () =&gt; () =&gt; console.log("hello")</span>

    outer()();

    <span class="hljs-comment">// Output: hello</span>
</code></pre>
<h3 id="heading-arrow-vs-regular-functions">Arrow vs Regular functions</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Arrow Function</strong></td><td><strong>Regular Function</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Arguments object is not available.</td><td>Arguments object is available.</td></tr>
<tr>
<td>Can not be used as a constructor.</td><td>Can be used as constructor.</td></tr>
<tr>
<td>Not hoisted</td><td>Hoisted</td></tr>
<tr>
<td>Short and clean structure</td><td>Longer syntax</td></tr>
<tr>
<td>Useful for callbacks, small utility functions</td><td>General purpose</td></tr>
</tbody>
</table>
</div><h3 id="heading-anonymous-vs-named-functions">Anonymous vs Named functions</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Anonymous Function</strong></td><td><strong>Named Function</strong></td></tr>
</thead>
<tbody>
<tr>
<td>No identifier, usually assigned to a variable to reuse</td><td>Has identifier to reuse</td></tr>
<tr>
<td>Difficult to debug, shows anonymous in call stack</td><td>Easy to debug</td></tr>
<tr>
<td>Not hoisted</td><td>Hoisted</td></tr>
<tr>
<td>Can’t be called recursively</td><td>Can be called recursively</td></tr>
<tr>
<td>Callbacks, expressions, IIFE</td><td>General purpose</td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[Closures & Scope in JavaScript]]></title><description><![CDATA[Ever wondered how functions remember their outer scope to execute? How scopes work in Javascript?
In this article, we will look at the core concepts like execution context, lexical environment, scope chaining and closures. These concepts define how J...]]></description><link>https://pblogs.hashnode.dev/closures-and-scope-in-javascript</link><guid isPermaLink="true">https://pblogs.hashnode.dev/closures-and-scope-in-javascript</guid><category><![CDATA[closure]]></category><category><![CDATA[scope chaining]]></category><category><![CDATA[Execution Context]]></category><category><![CDATA[lexical environment]]></category><category><![CDATA[Scope]]></category><category><![CDATA[call stack]]></category><category><![CDATA[heap]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Tue, 29 Jul 2025 17:39:08 GMT</pubDate><content:encoded><![CDATA[<p>Ever wondered how functions remember their outer scope to execute? How scopes work in Javascript?</p>
<p>In this article, we will look at the core concepts like execution context, lexical environment, scope chaining and closures. These concepts define how Javascript execution works at its core.</p>
<p>Let’s look at them one by one:</p>
<ul>
<li><p>Execution context(EC): Javascript runs on a call stack. Execution context can be seen as a stack frame created on the stack when a function starts its execution. It holds all the resources needed to execute that particular function. Few things to remember about EC:</p>
<p>  - It holds reference to the lexical environment and the this keyword.</p>
<p>  - There is a global execution context and a local execution context per function call.</p>
</li>
<li><p>Lexical environment(LE): It is an object in heap which contains the record of all the variables present in a function. It also holds the reference to its parent lexical environment.</p>
<p>  - It contains variables and parent LE reference stored in [[OuterEnv]].</p>
<p>  - Each block leads to creation of a new LE.</p>
<p>  - LE actually makes scoping possible in Javascript.</p>
</li>
<li><p>Scope: Scopes define the visibility area of a variable.</p>
<p>  - Each block has its own scope.</p>
<p>  - Inner scope has access to its outer scope but vice versa is not true. So a block have access to variables present in that particular block and the parent block.</p>
</li>
<li><p>Scope chaining: Each scope has access to its parent and this goes on till the global scope which doesn’t have a parent. So, each lexical environment has a reference to its parent LE, this forms a chain which is referred to as a scope chain. Global LE has parent reference set to null.</p>
</li>
<li><p>Closure: Functions, unlike other blocks, can exist even when the execution context which defined that function is destroyed. Functions are actually objects and their reference can be passed across the execution contexts and they need the outer scope from where they were defined to execute. To resolve this issue, an internal property [[Environment]] is added to function when it is defined which holds the reference to the outer LE. So when that function executes, an EC is created along with LE. EC holds reference to LE and LE holds reference to the parent - [[OuterEnv]] which is taken from [[Environment]] property of function. So, the function wrapped with reference to its outer scope(LE) - [[OuterEnv]] is what we refer to as a closure.</p>
</li>
</ul>
<p>Now, let’s look at the complete execution flow:</p>
<ol>
<li><p>Javascript creates a global execution context to start with. In creation phase it reserves the spot for each variable, these variables are stored in heap inside LE. It creates a LE for each block and references to these LE are stored in the EC. Along with it EC also stores the <em>this</em> reference. It sets parent of each LE accordingly and null is set for the global.</p>
</li>
<li><p>When a function definition is encountered, it creates an object for the function and stores the parent LE reference inside it forming a closure.</p>
</li>
<li><p>It updates these LE on the heap during the execution phase.</p>
</li>
<li><p>When a function execution starts, a separate execution context and lexical environment is created. EC holds reference to the LE. LE gets the parent from closure.</p>
</li>
<li><p>If an inner function is defined inside, a closure is formed for it.</p>
</li>
<li><p>Function completes its execution and EC is destroyed but LE still remains as it is referenced by the inner function’s closure.</p>
</li>
<li><p>Now when inner function executes same steps are followed.</p>
</li>
<li><p>Lexical environments are cleaned by garbage collector when no reference points to them.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753809757616/950dfd8a-7a66-446b-aa78-b0676cba924b.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[How to deal with passwords?]]></title><description><![CDATA[It is important to plan meticulously how you deal with passwords in your application. Passwords are one of the most sensitive entities of a system, which can pause major issues if compromised.
First, we must know passwords can be compromised in two w...]]></description><link>https://pblogs.hashnode.dev/how-to-deal-with-passwords</link><guid isPermaLink="true">https://pblogs.hashnode.dev/how-to-deal-with-passwords</guid><category><![CDATA[Security]]></category><category><![CDATA[Hashing]]></category><category><![CDATA[salt]]></category><category><![CDATA[encryption]]></category><category><![CDATA[passwords]]></category><category><![CDATA[Bcrypt ]]></category><category><![CDATA[rainbow-table ]]></category><category><![CDATA[stretching]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Wed, 23 Jul 2025 17:22:18 GMT</pubDate><content:encoded><![CDATA[<p>It is important to plan meticulously how you deal with passwords in your application. Passwords are one of the most sensitive entities of a system, which can pause major issues if compromised.</p>
<p>First, we must know passwords can be compromised in two ways:</p>
<ol>
<li><p>Over client side - Various attacks like phishing, etc. can steal the passwords even before they reach the server for processing. Passwords are often passed as plaintext over the network, therefore if an attackers get their hands on these plaintext, they can enter the system and modify resources. But, often these attacks are ignored while securing passwords as the impact is low. Few compromised passwords don’t affect the system significantly.</p>
</li>
<li><p>Over the server side - When database storing all the passwords gets compromised, it pauses significant impact on system’s security. Therefore, we usually deal with how to store the passwords, so that even if the DB gets attacked, attackers are not able to retrieve the original passwords.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753290163900/7e9a0381-48e9-406c-a3b2-53d5d8d0bdf3.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>Below are some techniques which helps deal with passwords securely:</p>
<ul>
<li><p>No plaintext, No encryption: Never store passwords in plaintext. Do not encrypt the passwords as it is reversible. If attacker gets hold of the key used for encryption and database, he can easily decrypt them.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753289477799/2f41ea48-867c-4f7a-a0b5-b84b5ac860b5.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Always hash the passwords: Use hashing techniques to convert your passwords in hash strings. This process is irreversible, so your system only remembers the hash and not the original password. When password needs to be verified during login, it recalculates the hash using the password entered by user and match it with hash stored in DB. This way, even if attacker hacks the DB, he won’t be able to extract password from it which is actually needed to login a system.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753289670345/a456d6da-5641-4c68-9ae1-3351ea549f19.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<blockquote>
<p>Hashing alone is not sufficient. <strong>Rainbow tables</strong> are the problem. These tables consists of hashes of some popular and common passwords. Hashses are precomputed so all attacker has to do is to search these hashes in compromised DB. This way, if a DB gets attacked, all the weak passwords gets hacked and these are a lot in practice.</p>
</blockquote>
<ul>
<li><p>Use a salt: Salt is an extra ingredient to your hashing technique. Salts are added with the passwords to make them less common and then hashed to store in DB. Example, “abc” is common but “abc69b238cb9f1d3844942d9b30e0a131ae” is not. Always use unique salt for each password and DO NOT use common salts like username, etc. You can store these salts with hashes in the DB.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753289896072/1257d2ec-ce7d-4ec0-9cc9-ce9faa7a6080.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<blockquote>
<p>Salts avoid rainbow table attacks, as now size of rainbow table increases significantly. Lets say there are n common hashes and 16 bit salt (2^16 possible salts) - imagine generating n * 2^16 hashes, practically infeasbile as their can be millions of leaked passwords(n). There will be 2^16 possible hashes for a single password.</p>
<p>But what if attacker combines rainbow table with brute force, target a user, get the salt from DB and generate the rainbow table using the targeted salt. To avoid this we need to make rainbow table precomputation infeasible.</p>
</blockquote>
<ul>
<li><p>Always use slow hashing algorithm: For hashing, slower the algorithm, more secure it will be. Avoid using MD5, SHA, etc. algorithms, use <strong>bcrypt</strong>, <strong>argon2, scrypt,</strong> <strong>PBKDF2,</strong> etc. instead. This makes precomputation of hashes harder.</p>
</li>
<li><p>Stretching: It is process of hashing a password repetitively for a number of times making the algorithm even more slower.</p>
</li>
<li><p>Use an existing algorithm rather than trying to reinvent the wheel, these algorithms are widely used and more secure.</p>
</li>
</ul>
<p>Above techniques make it infeasible for an attacker to hack the passwords with precomputed rainbow tables or precompute the table himself.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753290957747/700cb28e-15c3-465d-8fe5-fa24c4601bcd.png" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="http://web.archive.org/web/20120114184424/http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html">Rainbow Tables</a></p>
<p><a target="_blank" href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">OWASP Cheatsheet</a></p>
]]></content:encoded></item><item><title><![CDATA[Variable Declarations in JS - let vs const vs var]]></title><description><![CDATA[This article focuses on the three important keywords that lets you define variables and constants in Javascript - var, let and const.
Before we dive into the working and behavior of these keywords, make sure you understand the concepts like execution...]]></description><link>https://pblogs.hashnode.dev/let-const-var</link><guid isPermaLink="true">https://pblogs.hashnode.dev/let-const-var</guid><category><![CDATA[let and const]]></category><category><![CDATA[var let const]]></category><category><![CDATA[Hoisting]]></category><category><![CDATA[closures in javascript]]></category><category><![CDATA[variables]]></category><category><![CDATA[constant]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Mon, 21 Jul 2025 18:55:40 GMT</pubDate><content:encoded><![CDATA[<p>This article focuses on the three important keywords that lets you define variables and constants in Javascript - var, let and const.</p>
<p>Before we dive into the working and behavior of these keywords, make sure you understand the concepts like execution context, scopes, lexical environment, hoisting, how Javascript behaves in different environments like Browser or Node.js, etc.</p>
<h3 id="heading-var"><strong>VAR</strong></h3>
<p>var is used to create a function scoped variable, that means it gets created when a functional block starts and can be accessed throughout it. Some key points to remember about var -</p>
<ul>
<li><p>It is function scoped, it isn’t aware of blocks other than the function which declared it.</p>
</li>
<li><p>It can be redeclared.</p>
</li>
<li><p>It can be used before its declaration as it is hoisted.</p>
</li>
</ul>
<h3 id="heading-letconst"><strong>LET/CONST</strong></h3>
<p>let and const are used to create a block scoped variable or constant, that means their access can be limited to a block not necessarily be a fucntion block. Some key points about let and const -</p>
<ul>
<li><p>They were introduced in ES6, before that everything was declared with var.</p>
</li>
<li><p>They are block scoped, that means they respect every subsequent block that is defined inside a function or module.</p>
</li>
<li><p>They can’t be redeclared.</p>
</li>
<li><p>They can’t be used before declaration, that doesn’t imply that they are not hoisted. let and const do get hoisted but they reside in an area referred to as TDZ(Temporal Dead Zone).</p>
</li>
</ul>
<blockquote>
<p>LET vs CONST</p>
<p>let - defines a variable, it can be updated.</p>
<p>const - defines a constant, once assigned it can’t be changed.</p>
</blockquote>
<h3 id="heading-examples">Examples</h3>
<p>Let’s look at some examples to understand above concepts -</p>
<pre><code class="lang-javascript">(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>) { <span class="hljs-comment">// block scope started</span>
            <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>; <span class="hljs-comment">// same variable</span>
        }
        <span class="hljs-built_in">console</span>.log(a);
    }
)(); <span class="hljs-comment">// Output - 20</span>

(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>) { <span class="hljs-comment">// block scope started</span>
            <span class="hljs-keyword">let</span> a = <span class="hljs-number">20</span>; <span class="hljs-comment">// new variable created for the block</span>
        }
        <span class="hljs-built_in">console</span>.log(a);
    }
)(); <span class="hljs-comment">// Output - 10</span>
</code></pre>
<pre><code class="lang-javascript">(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
    }
)(); <span class="hljs-comment">// Executes fine</span>

(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">20</span>;
    }
)(); <span class="hljs-comment">// Throws error - Identifier 'a' has already been declared</span>
</code></pre>
<pre><code class="lang-javascript">(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
        <span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;
    }
)(); <span class="hljs-comment">// Output - undefined</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(a);
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    }
)(); <span class="hljs-comment">// Throws error - Cannot access 'a' before initialization</span>
</code></pre>
<pre><code class="lang-javascript">(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
        a = <span class="hljs-number">20</span>;
        <span class="hljs-built_in">console</span>.log(a);
    }
)(); <span class="hljs-comment">// Output - 20</span>

(
    <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">const</span> a = <span class="hljs-number">10</span>;
        a = <span class="hljs-number">20</span>;
        <span class="hljs-built_in">console</span>.log(a);
    }
)(); <span class="hljs-comment">// Throws error - Assignment to constant variable.</span>
</code></pre>
<h3 id="heading-browser-vs-node-environment">Browser vs Node environment</h3>
<p>Javascript behaves differently in Browser and Node environment, let’s look at them one by one:</p>
<p><strong>Node environment</strong></p>
<p>In Node.js, a JS file is wrapped as a module. So variables defined globally in Node.js get bounded by a module and can be accessed inside that module but not outside it. They are not added to global scope(global variable) and is actually function scoped.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-keyword">var</span> b = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">global</span>.a);
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">global</span>.b)

<span class="hljs-comment">/* Output:
undefined
undefined
*/</span>
</code></pre>
<p><strong>Browser environment</strong></p>
<p>Variables defined globally inside a script loaded in browser are truly global. They get added to the global scope. But var and let/const behave a bit differently. While they all lie in the same global scope, var gets added to the global object - window but let/const don’t.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-keyword">var</span> b = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.a);
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.b)

<span class="hljs-comment">/* Output:
undefined
20
*/</span>
</code></pre>
<p>Scripts execute in the order in which they are embedded in HTML. So variables defined outside all functions in script files go to global scope and can be accessed across all the scripts.</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-built_in">console</span>.log(a);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>

<span class="hljs-comment">/* console - 10 */</span>
</code></pre>
<p>Finally, lets look at some problems paused by var(leading to use of let/const):</p>
<ul>
<li><p>var doesn’t allow to declare a constant.</p>
</li>
<li><p>It can be accessed without initialization returning undefined.</p>
</li>
<li><p>It can be redeclared which may lead to accidental overwrites.</p>
</li>
<li><p>Doesn’t behave as expected with closures.</p>
</li>
</ul>
<p>Example</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(i), <span class="hljs-number">100</span>);
}
<span class="hljs-comment">// Prints: 3, 3, 3</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(i), <span class="hljs-number">100</span>);
}
<span class="hljs-comment">// Prints: 0, 1, 2</span>
</code></pre>
<p>In first example, var is the same in each iteration and doesn’t get redeclared, therefore, callbacks to setTimeout closes over the same variable which is at the end updated to 3. So, when executed all returns 3.</p>
<p>On the other hand, let forces it to get redeclared for each iteration, therefore, callbacks closes over different variables. So, when executed, prints their respective closure variables.</p>
]]></content:encoded></item><item><title><![CDATA[Hoisting Explained]]></title><description><![CDATA[Javascript executes in two phases:

Creation Phase: In this phase, JS allocates space in memory for all the variables, constants, functions, etc. This phase actually creates the execution contexts.

Execution phase: In this phase, all the assignments...]]></description><link>https://pblogs.hashnode.dev/hoisting-explained</link><guid isPermaLink="true">https://pblogs.hashnode.dev/hoisting-explained</guid><category><![CDATA[Hoisting]]></category><category><![CDATA[let and const]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Mon, 21 Jul 2025 17:28:30 GMT</pubDate><content:encoded><![CDATA[<p>Javascript executes in two phases:</p>
<ol>
<li><p>Creation Phase: In this phase, JS allocates space in memory for all the variables, constants, functions, etc. This phase actually creates the execution contexts.</p>
</li>
<li><p>Execution phase: In this phase, all the assignments, function calls, etc. are executed using the context created in previous phase.</p>
</li>
</ol>
<p>So, Hoisting is actually Javascripts mechanism of gathering all the variables, constants, etc. that will be required in a function and allocate their space in the memory. It doesn’t initialize in the creation phase, variables remain undefined.</p>
<p>Lets take an example to understand it better,</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753107762941/48e2f4ec-8ca0-47e3-8e5d-cf4f056121ad.png" alt class="image--center mx-auto" /></p>
<p>Lets look at each one:</p>
<ul>
<li><p>let/const - gets hoisted but resides in the Temporal Dead Zone(TDZ) and can’t be accessed.</p>
</li>
<li><p>var - hoisted and set to undefined, can be accessed.</p>
</li>
<li><p>function definitions - hoisted, therefore, functions can be called anywhere in the scope.</p>
</li>
<li><p>function assignments - only the variable holding the function gets hoisted and set to undefined.</p>
</li>
<li><p>class definition - hoisted, but can’t be initialized constructor is not yet available.</p>
</li>
</ul>
<p>Lets understand it by taking a few more examples:</p>
<pre><code class="lang-javascript">f();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
}

<span class="hljs-comment">/* Output: Hello
f gets hoisted during creation phase, hence it is available in execution phase before 
definition.
*/</span>
</code></pre>
<pre><code class="lang-javascript">f();
<span class="hljs-keyword">const</span> f = <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"</span>);
}
<span class="hljs-comment">/* Throws error: Cannot access 'f' before initialization
f variable gets hoisted during creation phase and set to undefined, it is not available until
it gets assigned in execution phase.
*/</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a);
<span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>;

<span class="hljs-comment">/* Output: undefined
a gets hoisted during creation and set to undefined 
*/</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a);
<span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-comment">/* Throws error: Cannot access 'a' before initialization
a gets hoisted but resided in TDZ and can't be accesses until initialized in execution phase
*/</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Person()
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Demo"</span>
    }
}
<span class="hljs-comment">/* Throws error: Cannot access 'Person' before initialization
class gets hoisted but not the constructor
*/</span>
</code></pre>
<p><strong><em>Hoisting</em></strong> <em>is JavaScript's behavior of</em> <strong><em>moving declarations to the top</em></strong> <em>of their enclosing scope during the compilation phase,</em> <strong><em>before</em></strong> <em>the code is actually executed.</em></p>
<p>Note that variables are not physically moved at the top rather it is logically percieved as they are available before the code actually starts execution.</p>
]]></content:encoded></item><item><title><![CDATA[How JavaScript Really Works Under the Hood]]></title><description><![CDATA[Synchronous Javascript (Javascript Engine)
Javascript is a synchronous language at its core, that means it runs on a single thread with a single call stack. So, all the code you write in core JS is executed line by line, one after the other on the sa...]]></description><link>https://pblogs.hashnode.dev/how-javascript-really-works-under-the-hood</link><guid isPermaLink="true">https://pblogs.hashnode.dev/how-javascript-really-works-under-the-hood</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Execution Context]]></category><category><![CDATA[callstack]]></category><category><![CDATA[callback functions]]></category><category><![CDATA[asynchronous JavaScript]]></category><category><![CDATA[promises]]></category><category><![CDATA[Event Loop]]></category><category><![CDATA[#microtaskqueue]]></category><category><![CDATA[ #TaskQueue ]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Sun, 20 Jul 2025 17:36:59 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-synchronous-javascript-javascript-engine">Synchronous Javascript (Javascript Engine)</h2>
<p>Javascript is a synchronous language at its core, that means it runs on a single thread with a single call stack. So, all the code you write in core JS is executed line by line, one after the other on the same call stack. It doesn’t skip to the next instruction until previous one is completed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753029349015/ef6cd8af-57ab-416e-85d9-568555b932d8.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-execution-context">Execution Context</h3>
<p>Execution context is an environment that Javascript uses to run the code. It starts off with a global execution context, and creates a new one for each function call. So, you can think of it as a separate environment for each function call that holds the space for variables used inside it.</p>
<p>Javascript creates a stack frame for each execution context in the call stack. To start with, a global execution context stack frame is added with all the global variables, including the global object - window, in case of browser and global, in case of Node environment. Then with each function call, a separate execution context is created and stacked at the top of the call stack. As soon as function completes its execution, its stack frame is popped out of the stack. Global execution context always resides in the stack at the bottom until the program is running.</p>
<p>Let’s take an example to understand the concept -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752851461324/1d0290a2-197a-486c-85c2-407bbb4fd0a3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753030553160/21728c99-b69f-46dd-8e9a-1d3a051f99ce.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-asynchronous-javascript-javascript-engine-browsernode-api">Asynchronous Javascript (Javascript Engine + Browser/Node API)</h2>
<p>When core Javascript is combined with Browser or Node APIs, its synchronous nature tends to shift to asynchronicity. Functions like setTimeout, fetch, etc. doesn’t execute instantly. So, the result for these operations is recieved after a while. Now, Javascript has 2 options whether to wait for the operation to complete(synchronous) or skip to the next one as the previous one keeps executing(asynchronous). Javascript goes with the asynchronous approach, but how does this get implemented? Do these operations run on separate threads or on the same with context switching? Who manages this asynchronous nature of JS?</p>
<p>Let’s look at these questions in detail.</p>
<p>First, lets look at some termonolgy required to understand the concepts:</p>
<p><strong>Promise</strong>: This is an object which eventually evaluates to success or failure but not at the moment. The operations like fetch which can’t complete instantly, returns a promise to complete. So, rather than returning a response, they return promise object. Think of it as a placeholder object, which when completed, gets replaced by the success or failure response.</p>
<p><strong>Callback:</strong> These are the functions which needs to be executed after these asynchronous operations complete.</p>
<p>Now, lets understand the components which really makes JS async:</p>
<ul>
<li><p><strong>Call Stack</strong>: This is the same stack we discussed above which take the function call one by one and executes them. So, Javascript has single thread, single call stack that runs everything.</p>
</li>
<li><p><strong>Web/Node APIs:</strong> These APIs are what makes JS asynchronous. They take some time to execute making JS switch to the next operation. Eg: setTimeout, fetch(Browser), file system(Node), etc.</p>
</li>
<li><p><strong>Task Queue:</strong> This a queue which holds all the callbacks.</p>
</li>
<li><p><strong>Event Loop:</strong> It checks the task queues and call stack constantly and pushes the callbacks to stack once its empty.</p>
</li>
<li><p><strong>Microtask Queue</strong>: This is also a task queue which holds callbacks but has higher priority. Callbacks for promises are pushed in it and gets executed before the task queue.</p>
</li>
</ul>
<p>Now, let’s look at the actual flow:</p>
<ol>
<li><p>Javascript runs as usual one operation after the other, all operations completing almost instantly.</p>
</li>
<li><p>It encounters fetch, which is part of Browser API and will take some time to complete.</p>
</li>
<li><p>It delegates this request to the Browser and moves to the next operation.</p>
</li>
<li><p>When Browser executes the request and fetch operation completes, the callback function along with the response is pushed into the queue.</p>
</li>
<li><p>Event loop checks the stack and queue regularly and pushes the callback in stack as soon as stack gets empty.</p>
</li>
<li><p>The call stack executes the callback.</p>
</li>
</ol>
<p>This way, Javascript along with the environment(Browser/Node) including task queues, event loops,etc. handles asynchronous tasks using a single call stack.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753031531471/a8aab4f1-2139-4231-bda4-bd05e650c180.png" alt class="image--center mx-auto" /></p>
<p>Following code demonstrate the complete flow:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Starting async function..."</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> { 
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Async operation complete..."</span>); <span class="hljs-comment">// Callback function body</span>
    }, <span class="hljs-number">0</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Async function complete..."</span>);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Starting execution..."</span>);
f();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Execution complete..."</span>);

<span class="hljs-comment">/* Output:
Starting execution...
Starting async function...
Async function complete...
Execution complete...
Async operation complete...
*/</span>
</code></pre>
<p>Microtask queue always gets precedence over task queue:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Starting async function..."</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"setTimeout complete..."</span>);
    }, <span class="hljs-number">0</span>);

    <span class="hljs-built_in">Promise</span>.resolve().then(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Promise complete..."</span>);
    })

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Async function complete..."</span>);

}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Starting execution..."</span>);
f();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Execution complete..."</span>);

<span class="hljs-comment">/* Output:
Starting execution...
Starting async function...
Async function complete...
Execution complete...
Promise complete...
setTimeout complete...
*/</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How DNS works?]]></title><description><![CDATA[DNS(Domain Name System) saves you from memorizing long IP addresses for different domains. It maintains records which maps these IP addresses into human-friendly names. For example, 172.64.146.196 the IP for ChatGPT’s server but you don’t need to rem...]]></description><link>https://pblogs.hashnode.dev/how-dns-works</link><guid isPermaLink="true">https://pblogs.hashnode.dev/how-dns-works</guid><category><![CDATA[dns]]></category><category><![CDATA[dns resolver]]></category><category><![CDATA[dns-records]]></category><category><![CDATA[dns server]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[networking]]></category><category><![CDATA[network]]></category><category><![CDATA[internet]]></category><category><![CDATA[url resolution]]></category><category><![CDATA[ip address]]></category><category><![CDATA[IP Addressing]]></category><dc:creator><![CDATA[Payal Rathee]]></dc:creator><pubDate>Fri, 18 Jul 2025 04:39:25 GMT</pubDate><content:encoded><![CDATA[<p>DNS(Domain Name System) saves you from memorizing long IP addresses for different domains. It maintains records which maps these IP addresses into human-friendly names. For example, 172.64.146.196 the IP for ChatGPT’s server but you don’t need to remember the IP**** you can simply type chat.com which gets mapped to the respective IP address.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752754229681/3784f39b-0f8a-4c9e-9aab-9c45147ec564.png" alt class="image--center mx-auto" /></p>
<p>Above diagram shows a high level overview of how DNS works, but there’s a lot going on under the hood. In this article we will understand how the flow goes from the domain request to actual repsonse from the server.</p>
<p>Few components of DNS that you need to know before we actually understand the flow:</p>
<h3 id="heading-dns-resolver"><strong>DNS Resolver</strong></h3>
<ul>
<li><p>It is a DNS server responsible to provide IP of requested domain to your OS.</p>
</li>
<li><p>Your ISP manages these DNS Resolvers and provides you services to resolve your domain names to a specific IP address.</p>
</li>
<li><p>Your OS have the IP address of DNS Resolver(obtained via DHCP) which is by default the IP of DNS provided by your ISP. But you can configure it manually to use any third party DNS like the one provided by google(8.8.8.8) or cloudfare(1.1.1.1).</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752755263062/2e3be1c6-8f8e-4fb2-ab6f-a6cfa03a1493.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>Google’s DNS Resolver has a unique IP address - 8.8.8.8, but that doesn’t mean there is physically one server reponsible to handle all the requests. Google hosts multiple DNS, It uses anycast to recieve request on the same IP, but your request actually goes to the DNS hosted nearest to you.</p>
<p>Some popular DNS tools - BIND, UNBOUND, dnsmasq, etc.</p>
</blockquote>
<h3 id="heading-root-dns">Root DNS [.]</h3>
<ul>
<li><p>These are the root DNS servers which holds addresses for the TLDs(Top Level Domain Servers).</p>
</li>
<li><p>There are around 13 Root DNS(virtually, there may be many more physically) A-M maintained by different orgzanizations -</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752756272768/a3c1a2fc-15d1-46f1-907a-3933cf07c181.png" alt class="image--center mx-auto" /></p>
<ul>
<li>You DNS resolver holds a list of these Root DNS servers.</li>
</ul>
<blockquote>
<p>New Root DNS servers are rarely added and their IPs remain almost constant.</p>
</blockquote>
<h3 id="heading-top-level-dns-tld-com-org-net">Top Level DNS (TLD) [.com, .org, .net…]</h3>
<ul>
<li><p>These DNS servers holds records for Authoritative DNS servers.</p>
</li>
<li><p>They are also maintained by different organizations like .com and .net are managed by Verisign, .org by Public Interest Registry (PIR), .in by NIXI (India), etc.</p>
</li>
<li><p>They fall into 3 major types:</p>
<ol>
<li><p>gTLDs (Generic): .com, .net, .org, etc.</p>
</li>
<li><p>ccTLDs (Country Code): .in, .us, .uk, etc.</p>
</li>
<li><p>Sponsored/Brand TLDs: .edu, .gov, etc.</p>
</li>
</ol>
</li>
</ul>
<blockquote>
<p>If a new TLD needs to be added for eg. .dev, an application needs to be submitted to ICANN which reviews and accepts it. Then it gets forwarded to IANA, which updates it into root zone file and propagates to all Root DNS operators. Similary, a request is submitted to IANA when a new TLD server is added for an existing domain.</p>
</blockquote>
<h3 id="heading-authoritative-dns-googlecom-chatcom">Authoritative DNS [google.com, chat.com,…]</h3>
<ul>
<li><p>These are the servers which actually holds the IP addresses of your domains.</p>
</li>
<li><p>They are usually maintained by your domain registrar like goDaddy, DigitalOcean, Namecheap, etc.</p>
</li>
</ul>
<blockquote>
<p>If you register a domain via a registrar, it provides you a Authoritative DNS server which keeps the IPs of your domain. It also registers your domain with TLD servers. You can manually add or update DNS records for your domain or subdomains. These records may take some time to propagate due to TTL set in the DNS Resolvers. DNS Resolvers keeps using the old cached IPs until a specific amount of time(TTL) after which a new request is made.</p>
</blockquote>
<p>So, when you type chat.com in your browser, following things go on in your system:</p>
<ol>
<li><p>Browser looks for the IP corresponding to chat.com in it’s cache, if not found, it asks the OS for the IP.</p>
</li>
<li><p>OS looks into its cache, if IP isn’t present in the cache it looks for the IP of DNS Resolver in config provided via DHCP and forwards the request.</p>
</li>
<li><p>Now DNS Resolver looks for the IP in it’s cache, failing which it picks IP of a Root DNS server from named.root file configured inside it and redirects the request to Root DNS server.</p>
</li>
<li><p>Root DNS looks for the Top Level domain records and returns a list of IP addresses corresponding to TLD servers for that particular domain(.com).</p>
</li>
<li><p>DNS Resolver gets the list of TLDs, it then sends the request to the nearest TLD.</p>
</li>
<li><p>TLD looks into its records and sends the IPs of authoritative servers holding records of the targeted domain(chat.com).</p>
</li>
<li><p>DNS Resolver gets the list of Authoritative server and sends the request to get actual IP.</p>
</li>
<li><p>Authoritative server looks into its records to get the IP of domain requested and returns it to DNS Resolver.</p>
</li>
<li><p>DNS Resolver then returns it to your OS which in turn gives it to browser and browser sends request to the intended IP.</p>
</li>
<li><p>Browser recieves the response and displays it.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752812896815/bbc47b2f-880e-4f9f-a875-a9217585b2ae.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item></channel></rss>