<?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[Puneet Patel]]></title><description><![CDATA[Puneet Patel]]></description><link>https://blog.puneetpatel.com</link><generator>RSS for Node</generator><lastBuildDate>Sun, 06 Sep 2026 12:04:57 GMT</lastBuildDate><atom:link href="https://blog.puneetpatel.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[In-depth Shallow Copy and Deep Copy]]></title><description><![CDATA[Hello readers, there might be scenarios where we as a programmer/developer want to copy the values of the variables and use that variable in another task. In this case, we need to copy the value of that variable into another variable.
In JavaScript t...]]></description><link>https://blog.puneetpatel.com/in-depth-shallow-copy-and-deep-copy</link><guid isPermaLink="true">https://blog.puneetpatel.com/in-depth-shallow-copy-and-deep-copy</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[array methods]]></category><category><![CDATA[Objects]]></category><category><![CDATA[object]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Puneet Patel]]></dc:creator><pubDate>Wed, 11 May 2022 22:56:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/CGnoRQZGWmw/upload/v1652309401414/zdP7QsT9u.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello readers, there might be scenarios where we as a programmer/developer want to copy the values of the variables and use that variable in another task. In this case, we need to copy the value of that variable into another variable.</p>
<p>In JavaScript there are two ways in which data is copied, namely:</p>
<h2 id="heading-pass-by-value">pass by value</h2>
<blockquote>
<p>The actual value is passed</p>
</blockquote>
<h2 id="heading-pass-by-reference">pass by reference</h2>
<blockquote>
<p>The memory location where the data is stored is passed</p>
</blockquote>
<p>Also, there are two types of data types in Javascript, namely:</p>
<h2 id="heading-primitive-data-type">primitive data type</h2>
<blockquote>
<p>This includes Boolean, NULL, undefined, String and Number</p>
</blockquote>
<h2 id="heading-reference-non-primitive-data-type">reference/ non-primitive data type</h2>
<blockquote>
<p>This includes Array, Objects and Functions.</p>
</blockquote>
<h2 id="heading-copy-by-equating">Copy by equating "="</h2>
<blockquote>
<p>The primitive data type values are copied by value, whereas the non-primitive data type values are copied by reference (i.e., the memory location of the data type is copied instead of the value)</p>
</blockquote>
<h3 id="heading-equating-in-case-of-primitive-data-type">Equating in case of primitive data type:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = <span class="hljs-string">"apple"</span>
<span class="hljs-keyword">const</span> copiedFruit = fruit
<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output:</p>
<pre><code class="lang-javascript">apple
apple
<span class="hljs-comment">// Nothing to consider in case of primitive data type</span>
</code></pre>
<p>Let's check in case of reference data types,</p>
<h3 id="heading-equating-in-case-of-reference-data-type">Equating in case of reference data type:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-keyword">const</span> copiedFruit = fruit    <span class="hljs-comment">// just reference to the memory location is copied</span>

copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>

<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output: </p>
<pre><code class="lang-javascript">Output: 
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]  <span class="hljs-comment">// source array got changed aswell</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]
</code></pre>
<p>Since this is copied by reference, changing the value of copiedFruit changes the value of fruit (source array) as well. This is true for the objects and the functions as well as shown in the above code snippet.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652297579262/_D43MrNBU.png" alt="array1.png" />
The image depicts that actually the object (array) reference is copied, i.e., the object (array) points to the same memory location.</p>
<p>But, we don’t want to mutate the source array or objects. 
This can be achieved by the following in-built javascript methods:</p>
<h2 id="heading-copy-by-using-javascript-methods">Copy by using Javascript Methods</h2>
<h3 id="heading-using-array-methods">Using array methods</h3>
<h4 id="heading-by-using-slice">By using slice()</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-keyword">const</span> copiedFruit = fruit.slice(<span class="hljs-number">0</span>)    <span class="hljs-comment">// creates an actual copy of array </span>

copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>

<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Output: </span>
[ <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]         <span class="hljs-comment">// didn't affected the source array</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]
</code></pre>
<h4 id="heading-by-using-es6-spread-operator">By using ES6 Spread operator:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// Only change in below line</span>
<span class="hljs-keyword">const</span> copiedFruit = [...fruit]   <span class="hljs-comment">// creates an actual copy of array </span>

copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>

<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Output: </span>
[ <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]         <span class="hljs-comment">// didn't affected the source array</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]
</code></pre>
<h4 id="heading-by-using-concat">By using concat()</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// Only change in below line</span>
<span class="hljs-keyword">const</span> copiedFruit = fruit.concat([])   <span class="hljs-comment">// creates an actual copy of array </span>

copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>

<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Output: </span>
[ <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]         <span class="hljs-comment">// didn't affected the source array</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]
</code></pre>
<h4 id="heading-by-using-arrayfrom">By using Array.from()</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// Only change in below line</span>
<span class="hljs-keyword">const</span> copiedFruit = <span class="hljs-built_in">Array</span>.from(fruit)   <span class="hljs-comment">// creates an actual copy of array </span>

copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>

<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Output: </span>
[ <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]         <span class="hljs-comment">// didn't affected the source array</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]
</code></pre>
<h3 id="heading-using-object-method">Using Object Method</h3>
<h4 id="heading-by-using-objectassign">by using Object.assign</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruitObj = {<span class="hljs-attr">name</span>: <span class="hljs-string">"apple"</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">"red"</span>};
<span class="hljs-keyword">const</span> copiedFruitObj= <span class="hljs-built_in">Object</span>.assign({}, fruitObj) <span class="hljs-comment">// creates an actual copy of array </span>

copiedFruitObj.color = <span class="hljs-string">"yellow"</span>

<span class="hljs-built_in">console</span>.log(fruitObj, copiedFruitObj)
</code></pre>
<p>Output</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Output: </span>
{ <span class="hljs-attr">name</span>: <span class="hljs-string">'apple'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span> }  <span class="hljs-comment">//fruitObj: didn't affected the source object</span>
{ <span class="hljs-attr">name</span>: <span class="hljs-string">'apple'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'yellow'</span> }   <span class="hljs-comment">//copiedFruitObj</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652298888131/SnUXG9vLO.png" alt="shallow.png" />
As shown in the image above, memory locations for <code>fruit</code> and <code>copiedFruit</code> are different and thus all the source reference data types are not mutated.</p>
<p>So far so good, but the problem arises when any of the reference data types have a nested array, object or function. Before discussing the problem let's talk about shallow copy.</p>
<blockquote>
<p>All the ways of copying arrays or objects discussed so far are performing the shallow copy.</p>
</blockquote>
<h2 id="heading-what-is-shallow-copy">What is SHALLOW COPY?</h2>
<p>According to the mdn docs,</p>
<blockquote>
<p>A <strong>shallow copy</strong> of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.</p>
</blockquote>
<p>Let’s understand shallow copy:</p>
<p>let’s take the same fruit array example from above:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [{<span class="hljs-attr">name</span>: <span class="hljs-string">"cherry"</span>},<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// In the fruit array the first element of the array is a reference data type (object)</span>
<span class="hljs-comment">// Now, replacing the first element</span>
<span class="hljs-keyword">const</span> copiedFruit = [...fruit]
copiedFruit[<span class="hljs-number">0</span>] = <span class="hljs-string">"orange"</span>;
<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output: </p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Output: </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'cherry'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]   <span class="hljs-comment">//fruit </span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]             <span class="hljs-comment">//copiedFruit: independent copy</span>
</code></pre>
<p>In the above snippet, still both the array are completely independent (the source array is not mutated due to the copied array), but the problem arises when the properties of the nested reference data type (array or object) are changed as shown in below code snippet.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [{<span class="hljs-attr">name</span>: <span class="hljs-string">"cherry"</span>},<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// In the fruit array the first element of the array is a reference data type (object)</span>
<span class="hljs-keyword">const</span> copiedFruit = [...fruit]
<span class="hljs-comment">// Now, changing the property of the nested reference data type</span>
copiedFruit[<span class="hljs-number">0</span>].name = <span class="hljs-string">"orange"</span>;      
<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output: </p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Output: </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'cherry'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]   <span class="hljs-comment">//fruit: source mutated</span>
[ <span class="hljs-string">'orange'</span>, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]             <span class="hljs-comment">//copiedFruit</span>
</code></pre>
<p>Let's break down how this is happening:
In Shallow Copy, as shown in image below,</p>
<ol>
<li>if the array elements or object keys value are of primitive data type, they are copied by values, and, </li>
<li>if the properties of the array elements or object keys values are of reference data type (array or object) they are copied by reference.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652302311995/Ft2bkhLCY.png" alt="shallow copy.png" /></p>
<p>So, now how can we create a completely independent copy of objects/arrays which don’t mutate the source object.
Here comes the deep copy,</p>
<h2 id="heading-what-is-deep-copy">What is DEEP COPY?</h2>
<p>According to the mdn docs,</p>
<blockquote>
<p>A <strong>deep copy</strong> of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.</p>
</blockquote>
<p>In simpler terms, copying the data stored from the source memory location to a new memory location by creating a completely independent object.</p>
<h3 id="heading-how-to-perform-deep-copy">how to perform deep copy?</h3>
<p><strong><em>Following are the ways to perform the deep copy:</em></strong></p>
<h4 id="heading-method-1-jsonparsejsonstringifyobject">METHOD 1: JSON.parse(JSON.stringify(object)))</h4>
<ul>
<li><strong><code>JSON.stringify()</code></strong> converts a JavaScript object into a JSON string and then returns it.</li>
<li><strong><code>JSON.parse()</code></strong> converts a JSON literal string into a JavaScript object and then returns it.</li>
</ul>
<p>Now, using the previous example and applying JSON.parse(JSON.stringify(object))</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [{<span class="hljs-attr">name</span>: <span class="hljs-string">"cherry"</span>},<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</span>];
<span class="hljs-comment">// In the fruit array the first element of the array is a reference data type (object)</span>
<span class="hljs-keyword">const</span> copiedFruit = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(fruit))
<span class="hljs-comment">// Now, changing the property of the nested reference data type</span>
copiedFruit[<span class="hljs-number">0</span>].name = <span class="hljs-string">"orange"</span>;      
<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output: </p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Output: </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'cherry'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]  <span class="hljs-comment">//fruit </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'orange'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span> ]  <span class="hljs-comment">//copiedFruit: independent copy</span>
</code></pre>
<p>This is fine, provides a deep copy and creates a new copy of data in a different memory location. </p>
<blockquote>
<p>But when Date, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types are used within your object, this method of cloning doesn't work as expected.
As shown in following code snippet:</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = [{<span class="hljs-attr">name</span>: <span class="hljs-string">"cherry"</span>},<span class="hljs-string">"apple"</span>, <span class="hljs-string">"mango"</span>, <span class="hljs-string">"banana"</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">"performs some task"</span>)}];
<span class="hljs-comment">// In the fruit array the first element of the array is a reference data type (object)</span>
<span class="hljs-keyword">const</span> copiedFruit = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(fruit))
<span class="hljs-comment">// Now, changing the property of the nested reference data type</span>
copiedFruit[<span class="hljs-number">0</span>].name = <span class="hljs-string">"orange"</span>;      
<span class="hljs-built_in">console</span>.log(fruit, copiedFruit)
</code></pre>
<p>Output: </p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Output: </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'cherry'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>, [<span class="hljs-built_in">Function</span>] ]  <span class="hljs-comment">//fruit </span>
[ { <span class="hljs-attr">name</span>: <span class="hljs-string">'orange'</span> }, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-literal">null</span> ]  <span class="hljs-comment">//copiedFruit: missing function</span>
</code></pre>
<p>Here as you can see in the above code snippet, the function is replaced by null, this method of the deep clone is not full proof!</p>
<h3 id="heading-what-is-the-full-proof-method-of-the-deep-clone">What is the full proof method of the deep clone?</h3>
<h4 id="heading-method-2-using-external-libraries">METHOD 2: Using external libraries:</h4>
<ul>
<li>Lodash:
It is a library that has a method called <a target="_blank" href="https://lodash.com/docs/4.17.15#cloneDeep">cloneDeep</a>, which does exactly what it states: Creates a deep clone of the reference data type passed and It also takes care of nested reference data types.</li>
</ul>
<p>Reference for clone deep:
<a target="_blank" href="https://www.geeksforgeeks.org/lodash-_-clonedeep-method/">cloneDeep Method</a></p>
<p>Summary:</p>
<ol>
<li>primitive data types are passed by value &amp; non-primitive data types are passed by reference.</li>
<li>In <strong><em>shallow cloning</em></strong>, the nested reference data types share the same memory location as their copied counterparts. JavaScript Methods like <strong>slice()</strong>, <strong>spread operator</strong>, <strong>concat()</strong>, <strong>Array.from()</strong> and  <strong>Object.assign()</strong> performs shallow cloning.</li>
<li><code>JSON.parse(JSON.stringify))</code> can perform <strong><em>deep cloning </em></strong> with exceptions of functions, date objects and so on, which when included doesn't give expected results.</li>
<li>To get full proof deep cloned object, an external library such as Lodash should be used which provides a <code>deepClone</code> method.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[call(), apply() and bind() methods in JavaScript]]></title><description><![CDATA[Hello readers, call, apply and bind methods are the most asked topic in JavaScript interviews as they are popularly used. Before directly heading towards the understanding of call, apply and bind methods, it is important to understand the "this" keyw...]]></description><link>https://blog.puneetpatel.com/call-apply-and-bind-methods-in-javascript</link><guid isPermaLink="true">https://blog.puneetpatel.com/call-apply-and-bind-methods-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[function]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Puneet Patel]]></dc:creator><pubDate>Wed, 11 May 2022 17:59:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/9DXo7yCT6mc/upload/v1652291273833/29teUF4A3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello readers, call, apply and bind methods are the most asked topic in JavaScript interviews as they are popularly used. Before directly heading towards the understanding of call, apply and bind methods, it is important to understand the "this" keyword and what it refers to.</p>
<h2 id="heading-this-keyword">"this" keyword</h2>
<blockquote>
<p><strong><em>this</em></strong> refers to the object that is executing the current piece of code.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1652201034438/kBbR4iFGk.png" alt="this.png" /></p>
<p>The above image depicts the Global execution context, it consists of the following:</p>
<ul>
<li>The global object: - In the browser, this is a window object.</li>
<li>"this" keyword: - this is referring to the global object</li>
<li>The variable environment: - a place in memory where variables live.</li>
<li>The outer environment: -When we execute code within a function the outer environment is the code outside that function — at the global level, it is null.</li>
</ul>
<p>"this" refers to different objects depending on how it is used:</p>
<ul>
<li>In an object method, this refers to the object.</li>
<li>Directly, this refers to the global object.</li>
<li>In an event, this refers to the element that received the event.</li>
<li>In a function, this refers to the global object.</li>
<li>In a function, in strict mode, this is undefined.</li>
</ul>
<p>For more details, check out mdn docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this</p>
<h2 id="heading-call-apply-and-bind">Call, Apply and Bind</h2>
<blockquote>
<p>Call, Apply and Bind are the method in Javascript and basically used to control what
<code>this</code> in a function points to. Also called function borrowing methods.</p>
</blockquote>
<p>Function borrowing allows us to use the methods defined in one object on a different object without making a copy of the method.</p>
<h3 id="heading-implicit-binding">Implicit Binding</h3>
<p>In JavaScript, implicit binding is already declared by the language. As shown in the code snippet below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"mango"</span>,
  <span class="hljs-attr">printFruit</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)  <span class="hljs-comment">// mango</span>
  }
}
fruit.printFruit()
</code></pre>
<h3 id="heading-explicit-binding">Explicit Binding</h3>
<p>In Explicit Binding, we explicitly point <code>this</code> of function to the object, both defined in the same level of scope.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"mango"</span>,
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printFruit</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-comment">// mango</span>
  }

printFruit.call(fruit)
</code></pre>
<p>In the above code snippet, object and function are defined in the global environment, by using the call() method we explicitly point <code>this</code> of the function (printFruit) to the object (fruit).</p>
<h3 id="heading-call-method"><code>call()</code> method</h3>
<blockquote>
<p>In the <code>call()</code> method, the context with which the function has to be called is passed as a parameter to the call.</p>
</blockquote>
<p>As shown In the fruit example above.</p>
<h4 id="heading-how-to-pass-multiple-parameters-in-the-call-method">How to pass multiple parameters in the call() method?</h4>
<p>In the same example of fruit, we can pass the arguments to the call method as shown in the snippet below:</p>
<p>Code snippet of the <code>call()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"mango"</span>,
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printFruit</span>(<span class="hljs-params">fruit2, fruit3</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name, fruit2, fruit3)  <span class="hljs-comment">// mango apple banana</span>
  }

printFruit.call(fruit, <span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>)
</code></pre>
<p>In the call() method, the first argument is the object with whose context the function is to be called and the following arguments are the values with are to be used in the function.</p>
<h3 id="heading-apply-method">apply() method</h3>
<blockquote>
<p><code>apply()</code> method is the same as the <code>call()</code>, except the second argument is passed as an array of values.</p>
</blockquote>
<p>Code snippet of the <code>apply()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"mango"</span>,
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printFruit</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name, args[<span class="hljs-number">0</span>], args[<span class="hljs-number">1</span>])  <span class="hljs-comment">// mango apple banana</span>
  }

printFruit.apply(fruit, [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>])
</code></pre>
<p>This makes it easier as we need to pass an array as an argument.</p>
<h3 id="heading-bind-method">bind() method</h3>
<blockquote>
<p><code>bind()</code> method is similar to <code>call()</code>, with one difference. Unlike the <code>call()</code> method invoking a function directly, the bind method returns the brand new function which can be stored and invoked as and when required.</p>
</blockquote>
<p>Code snippet of the <code>bind()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"mango"</span>,
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printFruit</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-comment">// mango </span>
  }

<span class="hljs-keyword">const</span> storedFunction = printFruit.bind(fruit)

storedFunction()
</code></pre>
<p>Here, the <code>printFruit.bind(fruit)</code> return a brand new function, which is stored in <code>storedFunction</code> and invoked on the next line when required.</p>
<h2 id="heading-summary">Summary</h2>
<ul>
<li>This keyword refers to different objects depending on how it is used.</li>
<li>In the case of implicit binding, <code>this</code> binds to the object adjacent to the dot(.) operator while invoking the method.</li>
<li>In the case of explicit binding, we can call a function with an object when the function is outside of the execution context of the object. This can be done using call(), apply() and bind(). </li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Event Bubbling, Event Capturing & Stop Propagation in JavaScript]]></title><description><![CDATA[Hello readers, before understanding event bubbling and capturing it is important to understand event propagation. If you are familiar with it skip to the event Bubbling section. 
Event Propagation

Event Propagation is a mechanism in which the event ...]]></description><link>https://blog.puneetpatel.com/event-bubbling-event-capturing-and-stop-propagation-in-javascript</link><guid isPermaLink="true">https://blog.puneetpatel.com/event-bubbling-event-capturing-and-stop-propagation-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[events]]></category><category><![CDATA[DOM]]></category><category><![CDATA[Script]]></category><dc:creator><![CDATA[Puneet Patel]]></dc:creator><pubDate>Thu, 05 May 2022 11:31:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1651744298342/SszJNpJdl.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello readers, before understanding <strong>event bubbling</strong> and <strong>capturing</strong> it is important to understand event propagation. If you are familiar with it skip to the event Bubbling section. </p>
<h2 id="heading-event-propagation">Event Propagation</h2>
<blockquote>
<p>Event Propagation is a mechanism in which the event propagates or <strong>travels</strong> through the DOM (Document Object Model) tree of a webpage.</p>
</blockquote>
<p>Event propagation occurs in three phases, this is called as Event Propagation Life Cycle:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651821897532/2NsHkajUR.png" alt="iEvent propagation life cycle" /></p>
<ol>
<li><strong>Capture Phase</strong>: The event travels starting from the document object (window), through the HTML element towards the target element.</li>
<li><strong>Target Phase</strong>: The event element reaches the target element which generated the event.</li>
<li><strong>Bubble Phase</strong>: The event travels from the target element, through its parent towards the window object.</li>
</ol>
<p>Now, as we have understood how an event flows in the DOM tree. Let's understand Event Bubbling and Capturing.</p>
<h2 id="heading-event-bubbling-and-capturing">Event Bubbling and Capturing</h2>
<blockquote>
<p>Event bubbling and capturing describes the order in which event propagation occurs when a nested child element receives an event trigger and both the child and the parent element have event handlers registered to it.</p>
</blockquote>
<h3 id="heading-setup">Setup</h3>
<p>let us understand this with an example:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"ancestor"</span>&gt;</span>
    ANCESTOR
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"parent"</span>&gt;</span>
      PARENT
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child"</span>&gt;</span>a<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child"</span>&gt;</span>b<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child"</span>&gt;</span>c<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"src/index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>This is the HTML code having elements in this order of nesting 
<code>body &gt; ul &gt; li</code> having corresponding id as <code>ancestor &gt; parent &gt; child</code></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#ancestor"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ancestor"</span>);
});

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#parent"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"parent"</span>);
});

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#child"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"child"</span>);
});
</code></pre>
<p>Now, each element is attached to an event listener which just logs its element id upon event trigger. for example, clicking on ancestor will log <code>ancestor</code> in the console.</p>
<p>This is the UI of the program, container a, b and c are the child elements.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651741185945/INCrPBHAC.png" alt="image.png" /></p>
<p>We can check how the event propagates upon clicking on the child element.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651740761531/JNSXLt_EL.gif" alt="default event propagation (3).gif" class="image--center mx-auto" /></p>
<p>As clear in the above animation, the event propagates from the child element to the ancestor element. ( child &gt;&gt; parent &gt;&gt; ancestor )</p>
<h3 id="heading-event-bubbling">Event Bubbling</h3>
<blockquote>
<p>When the event propagates from the child or target element to the window object such a mode of event propagation is called Event Bubbling.</p>
</blockquote>
<p>Event bubbling is the default mode of event propagation. And thus in the example above for event bubbling, the order of propagation was:</p>
<h4 id="heading-on-clicking-child-element">On clicking child element:</h4>
<ol>
<li>first event listener of the child element receives the event.</li>
<li>second, the parent and </li>
<li>third, the ancestor.</li>
</ol>
<p>Thus, logs in the console for clicking on child element would be:</p>
<pre><code class="lang-html">child
parent
ancestor
</code></pre>
<h4 id="heading-on-clicking-parent-element">On clicking parent element:</h4>
<ol>
<li>first event listener of the parent element receives the event and</li>
<li>second, the ancestor.</li>
</ol>
<p>Thus, logs in the console for clicking on the parent element would be:</p>
<pre><code class="lang-html">parent
ancestor
</code></pre>
<p>Note: event bubble doesn't occur on every element, there are exceptions like focus, blur and scroll events where an event bubble is not observed.</p>
<h3 id="heading-syntax-for-event-handling-addeventlistener">Syntax for Event handling (addEventListener)</h3>
<p>Syntax: <code>target.addEventListener(type, listener , useCapture);</code></p>
<ul>
<li>type: A case-sensitive string representing an event type to listen for. In this example <code>'click'</code></li>
<li>listener:  An object that implements the Event interface when an event of the specified type occurs.</li>
<li>useCapture (Optional): A Boolean denoting whether events of this type will be delivered to the registered listener before being delivered to any EventTarget beneath it in the DOM tree.<blockquote>
<p>If boolean not specified, useCapture defaults to false. i.e. Event Bubbling is enabled.</p>
</blockquote>
</li>
</ul>
<h3 id="heading-event-capturing">Event Capturing</h3>
<blockquote>
<p>When the event propagates from the document object to the target element such a mode of event propagation is called Event Capturing.</p>
</blockquote>
<p>For observing event capturing, we need to specify the third argument of the <code>addEventListener</code> as a <code>true</code>.
so, the syntax would become: 
Syntax: <code>target.addEventListener(type, listener , true);</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651743497848/8B7ILqJnO.gif" alt="event capturing.gif" /></p>
<h4 id="heading-on-clicking-the-child-element">On clicking the child element:</h4>
<ol>
<li>first event listener of the ancestor element receives the event.</li>
<li>second, the parent and </li>
<li>third, the child.</li>
</ol>
<p>Thus, logs in the console for clicking on child element would be:</p>
<pre><code class="lang-html">ancestor 
parent
child
</code></pre>
<h4 id="heading-on-clicking-parent-element">On clicking parent element:</h4>
<ol>
<li>first event listener of the ancestor element receives the event and</li>
<li>second, the parent.</li>
</ol>
<p>Thus, logs in the console for clicking on the parent element would be:</p>
<pre><code class="lang-html">ancestor
parent
</code></pre>
<h2 id="heading-stop-propagation">Stop Propagation</h2>
<blockquote>
<p>The <strong>stopPropagation()</strong> method of the <strong>event interface</strong> prevents further propagation of the current event during the event propagation.</p>
</blockquote>
<p>for example: If we don't want the event to propagate to the ancestor in our example, we can call the stopPropagation method on the event we get in the callback() function of the addEventListener.</p>
<p>Code snippet for this case:</p>
<pre><code class="lang-javascript">  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#ancestor"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ancestor"</span>);
});

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#parent"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">parentEvent</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"parent"</span>);
  parentEvent.stopPropagation();
});

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#child"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"child"</span>);
});
</code></pre>
<p>In the parent element's event listener, we get an event interface, it is named as parentEvent here, upon which we called the stopPropagation method this will prohibit event propagation from the parent element implicating that the event has been completed successfully and no further propagation of event is required.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651745228646/VcqIPWmIg.gif" alt="stop propagation.gif" /></p>
<p>As you noticed in the above example, when we click on the child element, first the event is received by the child element, and output is logged in the console but as soon as it encounters e.stopPropagation() in the parent event listener, it stops further propagation and does not bubble up in the DOM tree.</p>
<h2 id="heading-event-handling-using-bubbling-capturing-and-stop-event-propagation">Event Handling using Bubbling, Capturing and Stop Event Propagation</h2>
<p>let's assume an example case, 
Consider we want to only trigger the parent element's event listener on click of the child element.</p>
<p>we can achieve this by using <code>useCapture</code> and <code>stopPropagation()</code> method.</p>
<p>Since the default case is the bubbling, on click of the child the first event received would be by a child element, but we don't want that.
So let's change the <code>useCapture</code> to <code>true</code> for each event listener to use Event Capturing.
Now, on clicking the child element the event received would be by the ancestor element, but we don't want this too.</p>
<p>So how can we get the event to be received by the parent element first?
The answer is to make the ancestor element listener to bubble, i.e., <code>useCapture</code> to <code>false</code></p>
<p>Let's implement this in the code, our code snippet would look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#ancestor"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ancestor"</span>);
  },
  <span class="hljs-literal">false</span>
);

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#parent"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"parent"</span>);
  },
  <span class="hljs-literal">true</span>
);

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#child"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"child"</span>);
  },
  <span class="hljs-literal">true</span>
);
</code></pre>
<p>Now let's check the output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651746618001/77Wkw7LiH.gif" alt="get parent event on child click.gif" /></p>
<p>As seen above, we are making the parent listener receive the event first but we don't want the event to propagate from the parent element. This can be achieved by calling the stopPropagation method on the event received by the parent element's event listener.</p>
<p>So, our code snippet would look as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#ancestor"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ancestor"</span>);
  },
  <span class="hljs-literal">false</span>
);

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#parent"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">(<span class="hljs-params">parentEvent</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"parent"</span>);
    parentEvent.stopPropagation();
  },
  <span class="hljs-literal">true</span>
);

<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#child"</span>).addEventListener(
  <span class="hljs-string">"click"</span>,
  <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"child"</span>);
  },
  <span class="hljs-literal">true</span>
);
</code></pre>
<p>Final Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1651747058884/KT3Azrw9v.gif" alt="only parent on child click.gif" class="image--center mx-auto" /></p>
<p>Thus, the desired output has been obtained. </p>
<p>This was just a basic example of how we can handle events using the event bubbling, the event capturing and the stop propagation method.</p>
<p>Here's the code sandbox link to try on your own: 
<a target="_blank" href="https://codesandbox.io/s/event-bubbling-and-event-capturing-j7ooyq">CodeSandbox Link</a></p>
<h2 id="heading-tldr">TLDR</h2>
<ul>
<li>Event Propagation is the flow of events on the event trigger in the DOM tree. It has three phases:- <strong><em>Capture phase</em></strong>, <strong><em>Target phase</em></strong> and <strong><em>Bubble phase</em></strong>.</li>
<li>In event bubbling the event bubbles up the DOM tree and in capturing the event trickles down the DOM tree.</li>
<li>few events like focus and blur don't bubble up.</li>
<li>event propagation could be changed from bubbling to capturing by setting the <code>useCapture</code> to <code>true</code> in the addEventListener.<ul>
<li>Syntax: <code>target.addEventListener(type, listener , true);</code></li>
</ul>
</li>
<li>event propagation could be controlled by using <code>useCapture</code> and <code>stopPropagation()</code> method on event interface.</li>
</ul>
]]></content:encoded></item></channel></rss>