<?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[Tahir Ahmed]]></title><description><![CDATA[I am a Frontend Developer primarily working on React Based Applications. Currently working as an Associate at PWC US Advisory.]]></description><link>https://blog.tahirahmedt.com</link><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Apr 2026 19:10:14 GMT</lastBuildDate><atom:link href="https://blog.tahirahmedt.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Devtools Guide: Using Sensors for Beginners]]></title><description><![CDATA[Developer tools provided by browsers are an invaluable asset for web developers. They enable us to quickly diagnose issues, edit HTML in real-time, and iterate on our web applications more efficiently. In this article, we will explore one such powerf...]]></description><link>https://blog.tahirahmedt.com/devtools-guide-using-sensors-for-beginners</link><guid isPermaLink="true">https://blog.tahirahmedt.com/devtools-guide-using-sensors-for-beginners</guid><category><![CDATA[devtools]]></category><category><![CDATA[#chrome_devtools]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Sat, 18 May 2024 06:23:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1716013413533/8fda0391-9387-4ab0-a4a0-ca64e8724d86.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Developer tools provided by browsers are an invaluable asset for web developers. They enable us to quickly diagnose issues, edit HTML in real-time, and iterate on our web applications more efficiently. In this article, we will explore one such powerful tool: the Sensors tab in Chrome DevTools.</p>
<h2 id="heading-scenario">Scenario</h2>
<p>Let's think of a scenario where we can use sensors.</p>
<p>We have a web app where we need to display a greeting to the user based on the time of day. The requirements are as follows:</p>
<pre><code class="lang-plaintext">User should be able to see contextual greeting based on time of the day.
1. "morning"
      if the time is between 00:00 to 11:59
2. "afternoon"
    if the time is between 12:00 to 16:59
3. "evening"
      if the time is between 17:00 to 23:59
</code></pre>
<p>Let's write some code for this:</p>
<p>Whenever we write code for such requirements, it is better to create a pure function. A pure function provides the same output for the same arguments and does not depend on any global variables.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">giveContextualGreeting</span>(<span class="hljs-params">date = new Date()</span>) </span>{
    <span class="hljs-keyword">const</span> hours = date.getHours();
    <span class="hljs-keyword">if</span>(hours &gt;= <span class="hljs-number">0</span> &amp;&amp; hours &lt; <span class="hljs-number">12</span>) 
        <span class="hljs-keyword">return</span> <span class="hljs-string">"morning"</span>
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(hours &gt;= <span class="hljs-number">12</span> &amp;&amp; hours &lt; <span class="hljs-number">17</span>) 
        <span class="hljs-keyword">return</span> <span class="hljs-string">"afternoon"</span>
    <span class="hljs-keyword">else</span> 
        <span class="hljs-keyword">return</span> <span class="hljs-string">"evening"</span> 
}
</code></pre>
<p>To test if this is working as intended, you can do one of the following:</p>
<ul>
<li><p>Push your code to a source code management tool and ask a teammate in a different location to test it.</p>
</li>
<li><p>Wait for the relevant time and test the function.</p>
</li>
</ul>
<p>Both methods take a lot of time and can slow down your app development.</p>
<p>To overcome this, you can make use of <strong>sensors.</strong></p>
<h2 id="heading-sensors">Sensors</h2>
<p>The Sensors tab allows you to emulate sensor input from various devices, providing a convenient way to test how your website responds to different sensor data. This is particularly useful when building features that rely on user location, device orientation, or touch input.</p>
<p>We will take a look at how we can override geolocation to simulate the user's location, including custom coordinates or preset cities</p>
<p>Lets run the function in console of the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716012283455/135e9f38-c4a7-43c1-a7ab-511c886df98f.png" alt class="image--center mx-auto" /></p>
<p>This returns the result for your location. Now to check for other location, open sensors in devtools.</p>
<ul>
<li><p>Open the "Inspect" window - right click and select inspect from the list or press <kbd>Command</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> on mac and <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> on Windows, Linux or Chromebook.</p>
</li>
<li><p>Open Sensors - press <kbd>Command</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> on mac and <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> on Windows, Linux or Chromebook.</p>
</li>
<li><p>You can select one of the options</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716012739264/5568b272-4c2f-4d44-b2e0-f56aad7794e0.png" alt class="image--center mx-auto" /></p>
<p>  Lets select "Tokyo"</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716013099209/c34b96ff-733c-44f5-bc56-9cfd364ac661.png" alt class="image--center mx-auto" /></p>
<p>  Lets select "Mountain View"</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1716013063954/b8643466-3582-4978-a41c-5a8a03ac49ac.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>Now you are done with the testing the function without having to wait for time or someone else in different location to help you out.</p>
<p>That's all for this article. Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Function Borrowing methods in JavaScript and their Polyfills]]></title><description><![CDATA[Hello everyone, I'm back again with a new article. 
In this article we will discuss and learn about the Function Borrowing methods - call(), apply() and bind(). These are called function borrowing methods because the this context for a function can b...]]></description><link>https://blog.tahirahmedt.com/function-borrowing-methods-in-javascript-and-their-polyfills</link><guid isPermaLink="true">https://blog.tahirahmedt.com/function-borrowing-methods-in-javascript-and-their-polyfills</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[vanilla-js]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Sat, 14 May 2022 12:31:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1652532234738/XzdUBD26U.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone, I'm back again with a new article. </p>
<p>In this article we will discuss and learn about the <strong>Function Borrowing methods</strong> - <code>call()</code>, <code>apply()</code> and <code>bind()</code>. These are called function borrowing methods because the <code>this</code> context for a function can be modified using these methods. Before we jump into this discussion about what these methods do, I think it is important to understand how <code>this</code> works in JavaScript.</p>
<h2 id="heading-this-in-javascript"><code>this</code> in JavaScript</h2>
<p>The value of <code>this</code> in JavaScript is calculated at runtime i.e. when the code is getting executed. At a global level, <code>this</code> value equals the <code>window</code> object. Inside a normal function in an object, <code>this</code> refers to the enclosing object and inside an arrow function it references the value of <code>this</code> from the enclosing lexical context</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>place</td><td>Value of this</td></tr>
</thead>
<tbody>
<tr>
<td>global level</td><td>equal window (global) object</td></tr>
<tr>
<td>normal functions</td><td>equal to global object</td></tr>
<tr>
<td>normal functions inside objects</td><td>the current object</td></tr>
<tr>
<td>arrow functions</td><td>value of <code>this</code> in the enclosing lexical context</td></tr>
</tbody>
</table>
</div><p>Let's understand all these with a simple example</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); 
<span class="hljs-comment">/**
 * window object
 */</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">normalFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}
normalFunction()
<span class="hljs-comment">/**
 * window object
 */</span>


<span class="hljs-keyword">const</span> arrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); 
};
<span class="hljs-comment">/**
 * Does not redefine this.
 * Equal to enclosing scope in this case the window object
 */</span>


<span class="hljs-keyword">const</span> objectWhichContainsNormalFunction = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"tahir"</span>,
  <span class="hljs-attr">printName</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>);
  },
};
objectWhichContainsNormalFunction.printName();
<span class="hljs-comment">/**
 * Points to the object containing the function
 * {
 *    name: "tahir",
 *    printName: f()
 * }
 */</span>

<span class="hljs-keyword">const</span> objectWhichContainsArrowFunction = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"tahir"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"ahmed"</span>,
  <span class="hljs-attr">printName</span>: <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
  },
  <span class="hljs-attr">printFullName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    (<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    })();
  },
};
objectWhichContainsArrowFunction.printName();
<span class="hljs-comment">/**
 * In this case the value of this will be equal to the window object.
 *  */</span>

 objectWhichContainsArrowFunction.printFullName();
<span class="hljs-comment">/**
 * `this` will be equal to the object `objectWhichContainsArrowFunction`
 * This is because the `printFullName()` is a normal function and it redefines 
 * `this` value to the object
 */</span>
</code></pre>
<p>With <code>this</code> concept being clear, let's dive into the function borrowing methods.</p>
<h2 id="heading-call"><code>call</code></h2>
<p><code>call</code> invokes the functions with a <code>this</code> context and arguments provided individually.</p>
<p>Let's understand it with an example. Consider an object person1 which is as below</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> person1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"john"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"doe"</span>,
  <span class="hljs-attr">printFullName</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">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>`</span>);
  },
};
person1.printFullName()
<span class="hljs-comment">// john doe</span>
</code></pre>
<p>There is another object person2, which does not have the <code>printFullName()</code> implementation. We can call <code>printFullName()</code> and provide person2 as the context.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> person2= { 
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Alfred"</span>, 
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Marshall"</span> 
}

<span class="hljs-comment">/**
 * Invoking call method below
 */</span>

person1.printFullName.call(person2);
<span class="hljs-comment">// Alfred Marshall</span>
</code></pre>
<p>It is a good practice to have these functions outside. We can pass additional arguments to the call function individually. </p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> person1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Justin"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Case"</span>,
};

<span class="hljs-keyword">const</span> person2 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Parsley"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Montanna"</span>,
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">salutation, message</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>!!! <span class="hljs-subst">${message}</span>`</span>);
}

greetUser.call(person1, <span class="hljs-string">"Mr"</span>, <span class="hljs-string">"Good Morning!"</span>);
<span class="hljs-comment">// Mr Justin Case!!! Good Morning!</span>

greetUser.call(person2, <span class="hljs-string">"Ms"</span>, <span class="hljs-string">"Good Morning!"</span>);
<span class="hljs-comment">// Ms Parsley Montanna!!! Good Morning!</span>
</code></pre>
<p>In the above example snippet, <code>greetUser()</code> function defined outside. It expects two arguments <code>salutation</code> and <code>message</code>. In <code>call</code> we pass these arguments individually.</p>
<h2 id="heading-apply"><code>apply</code></h2>
<p><code>apply()</code> is similar to the <code>call()</code> method with the only difference being the way in which additional arguments are passed to the function while it is invoked. </p>
<p>In the case of <code>apply()</code> we pass all our arguments as an array</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> person1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Justin"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Case"</span>,
};

<span class="hljs-keyword">const</span> person2 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Parsley"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Montanna"</span>,
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">salutation, message</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>!!! <span class="hljs-subst">${message}</span>`</span>);
}

greetUser.apply(person1, [<span class="hljs-string">"Mr"</span>, <span class="hljs-string">"Good Morning!"</span>]);
<span class="hljs-comment">// Mr Justin Case!!! Good Morning!</span>

greetUser.apply(person2, [<span class="hljs-string">"Ms"</span>, <span class="hljs-string">"Good Morning!"</span>]);
<span class="hljs-comment">// Ms Parsley Montanna!!! Good Morning!</span>
</code></pre>
<h2 id="heading-bind"><code>bind</code></h2>
<p><code>bind</code> creates a new function and returns the function with the newly bound <code>this</code> context. It attaches the value of <code>this</code> passed as an argument to the function and returns the function.</p>
<p>Let us understand this with an example. We have an object named <code>user</code> and the function <code>greetUser()</code> within the object. Consider we have an admin role too and there is an object for that. Instead of defining a new function altogether, we can <em>bind</em> the <code>greetUser()</code> of the user object to the <code>admin</code> object and create a new function.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">fName</span>: <span class="hljs-string">"Kevin"</span>,
  <span class="hljs-attr">sName</span>: <span class="hljs-string">"Edwards"</span>,
}

<span class="hljs-keyword">const</span> greetUser =  <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">`Welcome <span class="hljs-subst">${<span class="hljs-built_in">this</span>.sName}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fName}</span>`</span>)
}

<span class="hljs-keyword">const</span> admin = {
  <span class="hljs-attr">fName</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">sName</span>: <span class="hljs-string">"Doe"</span>,
}

<span class="hljs-keyword">const</span> greetAdmin = greetUser.bind(admin)

greetAdmin()
<span class="hljs-comment">// Welcome Doe, John</span>
</code></pre>
<h2 id="heading-polyfills-for-call-apply-and-bind">Polyfills for <code>call()</code>, <code>apply()</code> and <code>bind()</code></h2>
<p>Polyfill, on its own, is a very vast concept. It would be too much information in a single article. In short, polyfills allow us to provide modern JavaScript functionalities in browsers that don't support them.</p>
<p><code>call()</code>, <code>apply()</code> and <code>bind()</code> are available on every function that we create in JavaScript. To make our own functions available in the same way, we have to define the functions on <strong>Function Prototype</strong>. For more information on what prototype is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">read here</a>.</p>
<h3 id="heading-polyfill-for-call">Polyfill for <code>call()</code></h3>
<p><code>call()</code> method calls a function with a new this context and other arguments that the function being called expects. The function would look something as below.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">Function</span>.prototype.myCall = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentContext = {}, ...args</span>) </span>{
  currentContext.fn = <span class="hljs-built_in">this</span>;
  currentContext.fn(...args);
};
</code></pre>
<p>Let us go through each line and understand what is happening. </p>
<ul>
<li>We are creating a polyfill called <code>myCall</code> and adding it to the <code>Function.prototype</code> so that it is available on all the functions. <ul>
<li><code>currentContext</code> is the object we want to call our function with</li>
<li><code>...args</code> - taking the rest of the parameters</li>
</ul>
</li>
<li>We then create a property <code>fn</code> on the <code>currentContext</code> object.</li>
<li><code>this</code> points to the function that is invoking or calling the <code>myCall()</code> function</li>
<li>We now call the function with its additional parameters by spreading them</li>
</ul>
<p>Consider the below example where we are using the above polyfill</p>
<pre><code class="lang-JS"><span class="hljs-built_in">Function</span>.prototype.myCall = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentContext = {}, ...args</span>) </span>{
  currentContext.fn = <span class="hljs-built_in">this</span>;
  currentContext.fn(...args);
};

<span class="hljs-keyword">const</span> person1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Justin"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Case"</span>,
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">salutation, message</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>!!! <span class="hljs-subst">${message}</span>`</span>);
}

greetUser.myCall(person1, <span class="hljs-string">"Mr"</span>, <span class="hljs-string">"Good Morning!"</span>);
<span class="hljs-comment">// Mr Justin Case!!! Good Morning!</span>
</code></pre>
<p>We are assigning the <code>greetUser()</code> function to <code>person1</code> object and redefining the <code>this</code> context to be the invoking object and calling it with the arguments.</p>
<h3 id="heading-polyfill-for-apply">Polyfill for <code>apply()</code></h3>
<p>We have seen that <code>call()</code> and <code>apply()</code> are similar except that <code>apply()</code> accepts all additional arguments to be in an array. So their polyfills are also similar</p>
<pre><code class="lang-JS"><span class="hljs-built_in">Function</span>.prototype.myApply = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentContext = {}, arg = []</span>) </span>{
  currentContext.fn = <span class="hljs-built_in">this</span>;
  currentContext.fn(...arg);
};
</code></pre>
<p>Instead of accepting all other arguments using the rest operator, we use a second parameter that accepts an array.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">Function</span>.prototype.myApply = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currentContext = {}, arg = []</span>) </span>{
  currentContext.fn = <span class="hljs-built_in">this</span>;
  currentContext.fn(...arg);
};

<span class="hljs-keyword">const</span> person2 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Parsley"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Montanna"</span>,
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">salutation, message</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${salutation}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>!!! <span class="hljs-subst">${message}</span>`</span>);
}

greetUser.myApply(person2, [<span class="hljs-string">"Ms"</span>, <span class="hljs-string">"Good Morning!"</span>]);
</code></pre>
<h3 id="heading-polyfill-for-bind">Polyfill for <code>bind()</code></h3>
<p><code>bind</code> returns a new function with a new <code>this</code> context. Before we delve into writing polyfill for <code>bind</code>, let's explore a bit more about how bind works</p>
<pre><code class="lang-JSX"><span class="hljs-keyword">const</span> admin = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Doe"</span>,
};

<span class="hljs-keyword">const</span> printDetails = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">city</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>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span> resides in <span class="hljs-subst">${city}</span>`</span>);
};

<span class="hljs-keyword">const</span> printDetailsOfAdmin = printDetails.bind(admin, <span class="hljs-string">"Doha"</span>);
printDetailsOfAdmin()

<span class="hljs-comment">// John Doe resides in Doha</span>
</code></pre>
<p>In the above codeblock we have an object <code>admin</code> and a function <code>printDetails</code>. When we write the polyfill we need to keep in mind that we have to return a function that can be called later. This function can take additional arguments which need to be passed on when we are returning the function. With these things in mind, let's get started. We will iteratively improve our <code>bind()</code> polyfill so that things are not confusing.</p>
<h4 id="heading-basic-version-of-bind-polyfill">Basic version of <code>bind()</code> polyfill</h4>
<pre><code class="lang-JSX"><span class="hljs-built_in">Function</span>.prototype.myBind = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">this</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    obj.call(args[<span class="hljs-number">0</span>]);
  };
}
</code></pre>
<p>This is a very basic implementation of <code>bind()</code> where we are returning a function that calls the method on which are binding the new object i.e., the new <code>this</code> context. </p>
<pre><code class="lang-JSX"><span class="hljs-keyword">const</span> printDetails = <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>.fname}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>`</span>);
};

<span class="hljs-keyword">const</span> admin = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Doe"</span>,
};

<span class="hljs-keyword">const</span> printAdminDetails = printDetails.myBind(admin)
</code></pre>
<p>Consider the above function and the subsequent call to myBind, then <code>this</code> in line 2 of the polyfill will be equal to the <code>printDetails()</code> function. We need to call the function with the object <code>admin</code> which can be done by accepting arguments using the rest operator and the first argument is the object which we need to pass accessible using <code>args[0]</code>. This version works fine as long as we don`t have any extra arguments. </p>
<h4 id="heading-avanced-version-of-bind-polyfill">Avanced version of <code>bind()</code> polyfill</h4>
<p>One of the very first changes that we need to do to pass other arguments too, is to replace <code>call</code> with <code>apply</code> the reason being we cannot keep track of how many extra arguments need to be passed. Now we need to pass the rest of the arguments apart from the object i.e., <code>args[0]</code> to the function that is getting returned</p>
<pre><code class="lang-JSX"><span class="hljs-built_in">Function</span>.prototype.myBind = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">this</span>;
  <span class="hljs-keyword">const</span> params = args.slice(<span class="hljs-number">1</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    obj.apply(args[<span class="hljs-number">0</span>], [...params]);
  };
};
</code></pre>
<p>Now let's try to see how it behaves when we use it on one of the objects </p>
<pre><code>const admin <span class="hljs-operator">=</span> {
  fname: <span class="hljs-string">"John"</span>,
  lname: <span class="hljs-string">"Doe"</span>,
};

const printDetails <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">city, country</span>) </span>{
  console.log(`${<span class="hljs-built_in">this</span>.fname} ${<span class="hljs-built_in">this</span>.lname} resides in ${city}, ${country}`);
};

const printDetailsOfAdmin <span class="hljs-operator">=</span> printDetails.myBind(admin, <span class="hljs-string">"Doha"</span>, <span class="hljs-string">"Qatar"</span>);
printDetailsOfAdmin()

<span class="hljs-comment">// John Doe resides in Doha, Qatar</span>
</code></pre><p>This totally works fine but consider the below scenario where we are passing the arguments when we are calling the <code>printDetailsOfAdmin()</code> function.</p>
<pre><code class="lang-JSX"><span class="hljs-keyword">const</span> printDetailsOfAdmin = printDetails.myBind(admin, <span class="hljs-string">"Doha"</span>);
printDetailsOfAdmin(<span class="hljs-string">"Qatar"</span>);

<span class="hljs-comment">// John Doe resides in Doha, undefined</span>
</code></pre>
<p>This is happening because we are not passing the arguments that we are receiving when the returned function gets called inside our polyfill.</p>
<pre><code class="lang-JSX"><span class="hljs-built_in">Function</span>.prototype.myBind = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">this</span>;
  <span class="hljs-keyword">const</span> params = args.slice(<span class="hljs-number">1</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...callerFunctionArgs</span>) </span>{
    obj.apply(args[<span class="hljs-number">0</span>], [...params, ...callerFunctionArgs]);
  };
};
</code></pre>
<p>This version of polyfill will work for all cases.</p>
<pre><code class="lang-JSX"><span class="hljs-keyword">const</span> printDetailsOfAdmin = printDetails.myBind(admin, <span class="hljs-string">"Doha"</span>);
printDetailsOfAdmin(<span class="hljs-string">"Qatar"</span>);

<span class="hljs-comment">// John Doe resides in Doha, Qatar</span>
</code></pre>
<p>That's all for this article. Thanks for reading. </p>
<p>You can follow me on my <a target="_blank" href="https://twitter.com/ttahm3d">Twitter</a> to be notified whenever I'm writing an article and keep updated with my journey in the world of web dev. Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[How to use CSS Modules in React]]></title><description><![CDATA[Hello everyone,
Hope you are doing well.
This will be a very small article where I will talk about how to get started with CSS Modules in React Apps. Without wasting much time lets get into it.
Problem with CSS
The CSS defintions in React are global ...]]></description><link>https://blog.tahirahmedt.com/how-to-use-css-modules-in-react</link><guid isPermaLink="true">https://blog.tahirahmedt.com/how-to-use-css-modules-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[CSS Modules]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Tue, 15 Mar 2022 12:59:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647350891183/JekF5LB0P.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone,</p>
<p>Hope you are doing well.</p>
<p>This will be a very small article where I will talk about how to get started with CSS Modules in React Apps. Without wasting much time lets get into it.</p>
<h2 id="heading-problem-with-css">Problem with CSS</h2>
<p>The CSS defintions in React are global scoped - meaning two or more classes with same name conflict with each other. Handling CSS becomes messy as the size of the project grows.</p>
<h2 id="heading-why-css-modules">Why CSS Modules?</h2>
<p>A CSS module is <code>.css</code> file where classes behave like Javascript variables. CSS Modules localize the <code>class</code> names and allow the users to use the same class names across the project. </p>
<p>They automatically create unique <code>className</code> for the <em>CSS class</em> using the format <code>[filename]\_[classname]\_\_[hash]</code> and scope the CSS classes locally. </p>
<p>For more information, <a target="_blank" href="https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/">read the docs</a>.</p>
<h2 id="heading-how-to-use-css-modules">How to use CSS Modules</h2>
<p>Using CSS modules is very easy. We need to name our files in the format <code>*.module.css*</code>. It is considered as a good practice to name the css module file with the same name as the component name in which it will be used.</p>
<pre><code><span class="hljs-operator">|</span>__Components
  <span class="hljs-operator">|</span>__Homepage
      <span class="hljs-operator">|</span>__Homepage.js
      <span class="hljs-operator">|</span>__Homepage.module.css
</code></pre><pre><code class="lang-scss"><span class="hljs-comment">// Define the classes normally as we define in normal css files</span>

<span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>:flex;
    <span class="hljs-attribute">flex-direction</span>: column;
    <span class="hljs-attribute">width</span>: min(<span class="hljs-number">90vw</span> - <span class="hljs-number">2em</span>, <span class="hljs-number">80em</span>);
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}
</code></pre>
<p>While using these classes we need to use the format <code>{styles.container}</code> where <code>styles</code> is the name which we are using to import and <code>container</code> is the css classname defined in our <code>.module.css</code> file. They are imported and used as shown below.</p>
<pre><code class="lang-JSX"><span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./Homepage.module.css"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Homepage</span>(<span class="hljs-params">props</span>) </span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.container}</span>&gt;</span>....content<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<h3 id="heading-using-more-than-one-css-class-for-a-component">Using more than one CSS class for a component</h3>
<p>It is not likely that all our css is written in one single class. We might have normal CSS classes coming from component libraries and other css module classes too. They can be used as below</p>
<pre><code>    <span class="hljs-operator">&lt;</span>div 
       className<span class="hljs-operator">=</span>{`${styles.classone} ${styles.classtwo} flex flex<span class="hljs-operator">-</span>column`}<span class="hljs-operator">&gt;</span>
        content
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
</code></pre><p><code>classone</code> and <code>classtwo</code> are classes defined in <code>*.module.css</code> file and <code>flex</code> and <code>flex-column</code> are normal css classes defined in component libraries.</p>
<p>Here is a link to <a target="_blank" href="https://codesandbox.io/s/immutable-framework-qo4l8c">Code Sandbox</a> where I have created two components and styled them using CSS modules.</p>
<p>That's all for this article.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Setting up testing for React Apps using jest & react-testing-library]]></title><description><![CDATA[Hello,
I'm back after a long time with another article. I had lot of interviews lined up as I was looking for switching job. Finally, accepted a position as Associate 2 at Pricewaterhouse Coopers.
So as one of the first tasks, I was asked to setup te...]]></description><link>https://blog.tahirahmedt.com/setting-up-testing-for-react-apps-using-jest-and-react-testing-library</link><guid isPermaLink="true">https://blog.tahirahmedt.com/setting-up-testing-for-react-apps-using-jest-and-react-testing-library</guid><category><![CDATA[Jest]]></category><category><![CDATA[React]]></category><category><![CDATA[Testing Library]]></category><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Mon, 15 Nov 2021 08:07:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638191494562/qUWbOSUzG.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello,</p>
<p>I'm back after a long time with another article. I had lot of interviews lined up as I was looking for switching job. Finally, accepted a position as Associate 2 at Pricewaterhouse Coopers.</p>
<p>So as one of the first tasks, I was asked to setup testing for react app that we were building using Jest and React Testing Library. I ran into multiple issues with the setup and could not find quick fixes for my problems. Just documenting what I did so that others don't feel or get stuck.</p>
<h3 id="heading-key-points-to-be-noted">Key Points to be noted</h3>
<ul>
<li>This solution is for projects being bundled with <strong>webpack</strong></li>
<li>This article is not for people who are bootstrapping the React App with <code>create-react-app</code> (hereby referred in the article as CRA). CRA comes preconfigured with <strong>jest</strong> and <strong>react-testing-library</strong>.</li>
<li>There are few things in this article which even I don't understand like creating stubs and various parameters in <code>jest.config.js</code> file</li>
<li>You have a basic knowledge of what packages like <strong>babel</strong> &amp; <strong>webpack</strong> do</li>
<li>You have a react project created using webpack. If not start by cloning using below command</li>
</ul>
<pre><code>git <span class="hljs-keyword">clone</span> -b <span class="hljs-number">01</span>-starter https:<span class="hljs-comment">//github.com/ttahm3d/react-javascript-template.git</span>
</code></pre><h2 id="heading-getting-started">Getting started</h2>
<p>As is the way with CRA template, most of the react app testing has been moved away from the combo of Jest and Enzyme to Jest and React Testing Library. Most of this due to the fact that enzyme does not support most of the new features of react and the delay in getting apapted to new features.</p>
<p>For someone coming from a Enzyme testing background, there is a complete shift in the testing point-of-view. We test the component for the way it works in React-Testing Library.</p>
<h2 id="heading-installation">Installation</h2>
<p>Jest is a javascript testing framework. It acts as a test runner and provides us methods to interact and assert if the expected results are correct or false.</p>
<pre><code>npm <span class="hljs-keyword">install</span> <span class="hljs-comment">--save-dev jest</span>
</code></pre><p>Let's check if it works by running the tests specified in the <a target="_blank" href="https://jestjs.io/docs/getting-started">Jest Docs</a></p>
<pre><code><span class="hljs-comment">// Sum.js</span>
<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">return</span> a + b;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Sum;

<span class="hljs-comment">// Sum.test.js</span>
<span class="hljs-keyword">import</span> Sum <span class="hljs-keyword">from</span> <span class="hljs-string">'./Sum'</span>;

test(<span class="hljs-string">'2 and 2 is 4'</span>, <span class="hljs-function">() =&gt;</span> {
  expect(Sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>)).toBe(<span class="hljs-number">4</span>);
});
</code></pre><p>Add the below settings to package.json</p>
<pre><code class="lang-JSON">    <span class="hljs-string">"scripts"</span>: {
        ...,
        <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>,
    },
</code></pre>
<p>Now run <code>npm run test</code>.</p>
<p>This test should work as expected. Lets install the other part of testing suite <em>react-testing-library</em> and start writing tests for our React components.</p>
<pre><code>npm install <span class="hljs-meta">@testing</span>-<span class="hljs-keyword">library</span>/react <span class="hljs-meta">@testing</span>-<span class="hljs-keyword">library</span>/jest-dom <span class="hljs-meta">@testing</span>-<span class="hljs-keyword">library</span>/user-event
</code></pre><h2 id="heading-configuration">Configuration</h2>
<p>Before we test React components we need to configure jest and react-testing-library.
Run the command:</p>
<pre><code>npx jest <span class="hljs-comment">--init</span>
</code></pre><p>You will be taken through a series of questions in the command line, answer them as per the applicability. For our instance the response is as below in the screenshot. After this is done, a <code>jest.config.js</code> file is created which has various parameters that are result of your choices.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636904561032/r-Poxyk49.png" alt="image.png" /></p>
<h2 id="heading-the-problem">The Problem</h2>
<p>Create a new test file <code>app.test.js</code> and the below contents</p>
<pre><code class="lang-JSX"><span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./app'</span>;

it(<span class="hljs-string">'should render the app component'</span>, <span class="hljs-function">() =&gt;</span> {
  render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
  <span class="hljs-keyword">const</span> text = screen.getByText(<span class="hljs-regexp">/React starter/i</span>);
  expect(text).toBeInTheDocument();
});
</code></pre>
<p>Now we see an error with error message on the as below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636907115841/i4vrBD8dv.png" alt="image.png" /></p>
<p>This is because jest cannot parse non Javascript files using babel loader. Files such as images, fonts, css files etc. need to be stubbed as per the jest documentation. We need to use the property called <a target="_blank" href="https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring"><code>moduleNameMapper</code></a> to stub these files.</p>
<h2 id="heading-solution">Solution</h2>
<p>Create a folder named Mocks and create two files <code>fileMock.js</code> and <code>styleMock.js</code></p>
<p>Add the below content to respective files</p>
<pre><code class="lang-JS"><span class="hljs-comment">// fileMock.js</span>
<span class="hljs-built_in">module</span>.exports = <span class="hljs-string">"test-file-stub"</span>;

<span class="hljs-comment">// styleMock.js</span>
<span class="hljs-built_in">module</span>.exports = {}
</code></pre>
<p>Now to the <code>jest.config.js</code> add the below content</p>
<pre><code class="lang-JS"><span class="hljs-built_in">module</span>.exports = {
...,
    <span class="hljs-attr">moduleNameMapper</span>: {
        <span class="hljs-string">"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$"</span>:
            <span class="hljs-string">"&lt;rootDir&gt;/Mocks/fileMock.js"</span>,
        <span class="hljs-string">"\\.(css)$"</span>: <span class="hljs-string">"&lt;rootDir&gt;/Mocks/styleMock.js"</span>,
    },
};
</code></pre>
<p>There is a new error now which is as below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636961531559/x4vlzMIdu.png" alt="image.png" /></p>
<p>Create a new file <code>setupTests.js</code> and add the following content</p>
<pre><code><span class="hljs-keyword">import</span> '@testing-library/jest-dom/extend-expect`
</code></pre><p>and add the below to <code>jest.config.js</code></p>
<pre><code><span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
   ...,
  setupFilesAfterEnv: [<span class="hljs-string">'&lt;rootDir&gt;/setupTests.js'</span>],
}
</code></pre><p>What this does it it calls the setupTests.js file before jest runs every <code>.test</code> file. Now the tests would run and pass.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636962632330/oVkFiEURv.png" alt="image.png" /></p>
<p>Complete soultion is in this <a target="_blank" href="https://github.com/ttahm3d/react-javascript-template">Git repo</a></p>
<p>Thats all for this article. Thanks for reading it through.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Objects in Javascript]]></title><description><![CDATA[I am currently interviewing for Frontend Developer roles and I failed one of the interviews because I was not good at Object Oriented Javascript. Writing this article to serve me as a goto article for any interview preparation in future and for other...]]></description><link>https://blog.tahirahmedt.com/introduction-to-objects-in-javascript</link><guid isPermaLink="true">https://blog.tahirahmedt.com/introduction-to-objects-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Sun, 18 Jul 2021 11:10:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1627279267708/wFOF4IpRW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I am currently interviewing for Frontend Developer roles and I failed one of the interviews because I was not good at Object Oriented Javascript. Writing this article to serve me as a goto article for any interview preparation in future and for others who want to learn. I have compiled all the resources from <a target="_blank" href="https://developer.mozilla.org/en-US/">MDN Docs</a>, <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#object-oriented-programming">FreeCodeCamp</a> and <a target="_blank" href="https://javascript.info">Javascript.info</a>.</p>
<p>Lets dive into the discussion without wasting time.</p>
<h2 id="primitive-and-non-primitive-data-types">Primitive and Non-primitive data-types</h2>
<p>There are 8 data types in Javascript</p>
<ul>
<li><code>number</code> - numbers of any kind</li>
<li><code>bigint</code> - numbers of large length</li>
<li><code>string</code> - set of characters wrapped within quotes (" " or ' ') or backticks (` `)</li>
<li><code>null</code> - unknown values</li>
<li><code>undefined</code> - unassigned values</li>
<li><code>boolean</code> - true  or false values</li>
<li><code>symbol</code> - for unique identifiers</li>
<li><code>object</code> - for complex data structures</li>
</ul>
<p>Refer <a target="_blank" href="https://javascript.info/types">here</a> for more information.</p>
<p>Except <code>object</code> all others are primitive datatypes. Objects are used to store collections of data in the form of key-value pairs.</p>
<h2 id="introduction-to-objects">Introduction to Objects</h2>
<p>A object is as simple as  <code>{}</code></p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">typeof</span> {} <span class="hljs-comment">//"object"</span>
</code></pre>
<h3 id="object-creation">Object creation</h3>
<p>Objects can be created in two ways</p>
<ol>
<li><p><strong>Object Construtor Syntax</strong></p>
<pre><code class="lang-JavaScript"> <span class="hljs-keyword">let</span> person = <span class="hljs-keyword">new</span> Person()
</code></pre>
</li>
<li><p><strong>Object Literal Syntax</strong></p>
<pre><code class="lang-JavaScript"> <span class="hljs-keyword">let</span> person = {}
</code></pre>
</li>
</ol>
<p>Objects usually have properties and methods. We can add properties into a object in the form <code>key:value</code>. Lets add two properties in <code>person</code> object</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span>
}
</code></pre>
<p><code>name</code> and <code>age</code> are the properties and <code>"john"</code> and <code>"24"</code> are their respective values.</p>
<h3 id="accessing-properties">Accessing properties</h3>
<h4 id="using-dot-notation">Using Dot (.) notation</h4>
<p>We can access the properties in the format <code>&lt;objectName&gt;.&lt;propertyName&gt;</code></p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span>
}

<span class="hljs-comment">// Accessing name</span>
<span class="hljs-built_in">console</span>.log(person.name) <span class="hljs-comment">// "john"</span>
<span class="hljs-built_in">console</span>.log(person.age) <span class="hljs-comment">// 24</span>
</code></pre>
<h4 id="using-square-brackets">Using Square ([]) brackets</h4>
<p>The square brackets come in handy when we have multi-word key i.e., object key with more than one word and has a space (' ') in between the words. </p>
<pre><code><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span>,
  <span class="hljs-string">"favourite language"</span>: <span class="hljs-string">"javascript"</span> <span class="hljs-comment">// note the special way in which key is defined</span>
}

<span class="hljs-built_in">console</span>.log(person[<span class="hljs-string">"name"</span>]) <span class="hljs-comment">// "john"</span>
<span class="hljs-built_in">console</span>.log(person[<span class="hljs-string">"favourite language"</span>]) <span class="hljs-comment">// "javascript"</span>
</code></pre><p>If we use the dot (.) notation to access multiword properties, JavaScript will throw an error. Javascript searches for property <code>favourite</code> in the object person. and then gives a syntax error when comes across unexpected <code>language</code>.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(person.favorite language)
</code></pre>
<p>The square bracket notation is also used to evaluate an expression and find a property of that result</p>
<pre><code><span class="hljs-keyword">let</span> key = <span class="hljs-string">"favourite language"</span>
<span class="hljs-built_in">console</span>.log(person[key]) <span class="hljs-comment">// javascript</span>
</code></pre><h3 id="adding-and-deleting-properties-to-objects">Adding and Deleting properties to objects</h3>
<p>We can add new properties to object using the dot notation after object has been created. To the same <code>person</code> object from above, we can add new property called <code>email</code> as below</p>
<pre><code class="lang-JS">person.email = <span class="hljs-string">"test@xyz.com"</span>

<span class="hljs-built_in">console</span>.log(person.email) <span class="hljs-comment">// test@xyz.com</span>
</code></pre>
<p>You can delete a property by object using <code>delete</code> followed by <code>&lt;objectName&gt;.&lt;propertyName&gt;</code></p>
<pre><code class="lang-JS"><span class="hljs-keyword">delete</span> person.age <span class="hljs-comment">// deletes age property</span>
</code></pre>
<h2 id="references-and-copying">References and copying</h2>
<p>Most questions in the interviews around the object, if you are beginner, will be around this topic</p>
<blockquote>
<p>The key difference between and primitive data types and objects is that Objects are stored and copied by reference</p>
</blockquote>
<p>Let us understand the above statement with below example</p>
<pre><code class="lang-JS"><span class="hljs-comment">// consider a variable of primitive type </span>
<span class="hljs-keyword">let</span> a = <span class="hljs-number">4</span>;

<span class="hljs-comment">// suppose you want to create a copy of the above variable</span>
<span class="hljs-keyword">let</span> b = a;

<span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// 4</span>
<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// 4</span>

<span class="hljs-comment">// at some point later in your code you change the value of a to be something else</span>
a = <span class="hljs-number">5</span>;

<span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// 4</span>
</code></pre>
<p>In the case of primitive data types the values are copied as a whole i.e., each variable has a separate location in the memory and contains its own copy of the value. The above example stands true for all primitive data types.</p>
<p>Now lets check similar scenario with Objects</p>
<pre><code class="lang-JS"><span class="hljs-comment">// consider a object person with name and email properties</span>

<span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">"john"</span>,
  <span class="hljs-attr">email</span> : <span class="hljs-string">"john@xyz.com"</span>
}

<span class="hljs-comment">// you want to make a copy of this object</span>

<span class="hljs-keyword">let</span> newPerson = person

<span class="hljs-comment">// you want to change the value of newPerson to be something else</span>

newPerson.name = <span class="hljs-string">"doe"</span>

<span class="hljs-built_in">console</span>.log(person.name) <span class="hljs-comment">// "doe"</span>
<span class="hljs-built_in">console</span>.log(newPerson.name) <span class="hljs-comment">// "doe"</span>
</code></pre>
<p>This happens because Objects are stored as references. There is a single object with parameters <code>name</code> and <code>email</code> in memory and refernced by two varaibles <code>person</code> and <code>newPerson</code>. We are making change to same object, hence those changes are reflected in both the variables.</p>
<h3 id="copying-objects">Copying Objects</h3>
<p>As we have seen above, normal copy just creates a refernce to the same object. If we want to create a separate clone of the object, we can loop through the entire object using <code>for...in</code> loop and copy each property. </p>
<h4 id="using-objectassign">Using Object.assign()</h4>
<p>The other way we can do it is using <code>Object.assign()</code> method. According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">MDN documentation</a>, it can be used to copy its <strong>own enumerable properties</strong>. It cannot be used to copy nested objects. The nested object is still copied as a reference.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">"john"</span>,
  <span class="hljs-attr">email</span> : <span class="hljs-string">"john@xyz.com"</span>
}

<span class="hljs-keyword">let</span> newPerson = {}
<span class="hljs-built_in">Object</span>.assign(newPerson, person)

newPerson.name = <span class="hljs-string">"doe"</span>

<span class="hljs-built_in">console</span>.log(person.name) <span class="hljs-comment">// "john"</span>
<span class="hljs-built_in">console</span>.log(newPerson.name) <span class="hljs-comment">// "doe"</span>
}
</code></pre>
<h4 id="using-spread-operator">Using Spread Operator (...)</h4>
<p>Spread operator was added in ES6. It is used to spread or expand an iterable such as array or object. It can be used to copy objects. This copies without reference.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>, <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span> }
<span class="hljs-keyword">const</span> newUser = {...user}
<span class="hljs-built_in">console</span>.log(newUser) <span class="hljs-comment">// { name: "john", age: "24" }</span>

newUser.name = <span class="hljs-string">"lewis"</span>
<span class="hljs-built_in">console</span>.log(newUser.name) <span class="hljs-comment">// "lewis"</span>
<span class="hljs-built_in">console</span>.log(user.name) <span class="hljs-comment">// "john"</span>
</code></pre>
<h4 id="deep-copying">Deep Copying</h4>
<p>Copying using <code>Object.assign()</code> and <code>Spread Operator (...)</code> does not copy the nested object - object which contains object in it. The nested part of object is still copied as a reference.</p>
<p>We can do a  <strong>Deep Copy</strong> of an object using <code>JSON.stringify()</code> and <code>JSON.parse()</code></p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"john"</span>, 
  <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span>, 
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">state</span>: <span class="hljs-string">"Texas"</span>,
    <span class="hljs-attr">country</span>: <span class="hljs-string">"USA"</span>
  }
}

<span class="hljs-keyword">const</span> newUser = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(user))
newUser.address.state=<span class="hljs-string">"California"</span>

<span class="hljs-built_in">console</span>.log(user) 
<span class="hljs-comment">// { name: "john", age: "24", address:{ state: "Texas", country: "USA" }}</span>
<span class="hljs-built_in">console</span>.log(newUser) 
<span class="hljs-comment">// { name: "john", age: "24", address:{ state: "California", country: "USA" }}</span>
</code></pre>
<h2 id="object-methods">Object Methods</h2>
<p>Objects along with properties have methods. Lets add a method <code>sayHello()</code> to our userobject.</p>
<pre><code class="lang-JavaScript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">"john"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-string">"24"</span>,
  <span class="hljs-attr">sayHello</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 class="hljs-subst">${user.name}</span>`</span>);
  }
}

user.sayHello() <span class="hljs-comment">// "Hello john"</span>
</code></pre>
<p>The idea behind having methods in objects is to allow only the methods to manipulate the object. The above code would work perfectly fine. But if the object is copied to another object and we call the <code>sayHello()</code> method, it will cause an error as it will try to access the method from another object.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">let</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
  sayHi() {
    <span class="hljs-built_in">console</span>.log( user.name ); <span class="hljs-comment">// leads to an error</span>
  }
};

<span class="hljs-keyword">let</span> admin = {...user};
user = <span class="hljs-literal">null</span>; <span class="hljs-comment">// overwrite to make things obvious</span>
admin.sayHi();
</code></pre>
<p>To overcome this, we need to use <code>this</code> keyword while refering any property of the object inside its method. <code>this</code> inside the method of an object refers to the enclosing object (the object in which the method is present).</p>
<p>The <code>this</code> behaves differently in JavaScript. Its value is evaluated at the run time depending upon the context. Please do give this <a target="_blank" href="https://javascript.info/object-methods#this-is-not-bound">article</a> a read. 
Arrow functions don't have their own <code>this</code>. <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#arrow_functions">They derive it from their enclosing Lexical Context</a></p>
<h2 id="constructors">Constructors</h2>
<p>So far we have seen how to create objects. What if we need to create multiple objects of the same type for example a list of users, list of todo items, we need to use Constructors along with <code>new</code> keyword to create objects. </p>
<p>Constructors are functions that create new objects - they define both the properties and methods that can act upon these properties. It serves as a blue print to the create objects. </p>
<p>Constructors are functions with just two conventions</p>
<ol>
<li>First letter of function should be capital</li>
<li>Constructors should be called only with <code>new</code> keyword</li>
</ol>
<pre><code class="lang-JS"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name,
  <span class="hljs-built_in">this</span>.age = age
}
</code></pre>
<p>The above snippet creates a Constructor with name <code>User</code>. Constructors use <code>this</code> keyword to set the properties of the new object. Here, <code>this</code> refers to the new object being created. The above Constructor defines two properties name and age and sets their values to the parameters in Constructor definition. </p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"john"</span>, <span class="hljs-string">"24"</span>)
<span class="hljs-built_in">console</span>.log(user.name) <span class="hljs-comment">// "john"</span>
</code></pre>
<p>We can create a new user as above. The <code>new</code> operator tells JavaScript to create a new instance of <code>User</code> object. Pass the values for name and age as arguments to the constructor call. We can have the methods in the constuctor function in the same way we have the methods in normal objects.</p>
<pre><code class="lang-JS"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name,
  <span class="hljs-built_in">this</span>.age = age,
  <span class="hljs-built_in">this</span>.sayHi = <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">`Hi <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>)
  }
}

<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"john"</span>, <span class="hljs-string">"24"</span>)
user.sayHi() <span class="hljs-comment">// "Hi john"</span>
</code></pre>
<h3 id="instance-of">Instance of</h3>
<p>When we create a new object using constructor, the new object is said to be instance of the constructor. This can be verified using instance of operator. It returns true if it is instance of the constructor</p>
<pre><code class="lang-JS"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name,
  <span class="hljs-built_in">this</span>.age = age,
  <span class="hljs-built_in">this</span>.sayHi = <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">`Hi <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>)
  }
}

<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"john"</span>, <span class="hljs-string">"24"</span>)
<span class="hljs-built_in">console</span>.log(user <span class="hljs-keyword">instanceof</span> User) <span class="hljs-comment">// true</span>
</code></pre>
<p>The <code>instanceof</code> operator can be used to distinguish between normal objects and objects created normally.</p>
<h2 id="call-apply-and-bind">Call, apply and bind</h2>
<p>The <code>this</code> keyword's value is calculated at the runtime. Inside a event listener or when the Object's method is passed as a callback to <code>setTimeout()</code>, <code>this</code> context is lost. The value of <code>this</code> will be the element that recieved the event in event listener function. I </p>
<p>To overcome this JavaScript provides, with <code>bind()</code> method. Along with <code>bind()</code> it is good to have idea about <code>call()</code> and <code>apply()</code> methods.</p>
<h3 id="call-and-apply">call() and apply()</h3>
<p>This is a function borrowing method in Javascript. The <code>call()</code> method calls a function with a given <code>this</code> context and arguments provided induvidually.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"john"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"doe"</span>,
  <span class="hljs-attr">getFullName</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 class="hljs-subst">${<span class="hljs-built_in">this</span>.lname}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span>`</span>) 
  }
}

user1.getFullName() <span class="hljs-comment">// "Hello doe, john"</span>
</code></pre>
<p>Consider there exists a object <code>user2</code> which does not have the getFullName implementation. We can call getFullName and provide user2 as the context.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user2  = { 
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Alfred"</span>, 
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Marshall"</span> 
}

user1.getFullName.call(user2) <span class="hljs-comment">// "Hello Marshall, Alfred"</span>
</code></pre>
<p>It is a good practice to have these functions outside. We can pass additional arguments to the call function induvidually. Apply works the same way as call but it takes the additional arguments in an array</p>
<pre><code><span class="hljs-keyword">const</span> user1 = {
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Doe"</span>,
}

<span class="hljs-keyword">const</span> greetNewJoiner = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">teamName, location</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>.lname}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fname}</span>`</span>) 
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`We are happy to welcome you to our <span class="hljs-subst">${location}</span> office and into <span class="hljs-subst">${teamName}</span> team`</span>)
}

<span class="hljs-keyword">const</span> user2  = { 
  <span class="hljs-attr">fname</span>: <span class="hljs-string">"Alfred"</span>, 
  <span class="hljs-attr">lname</span>: <span class="hljs-string">"Marshall"</span> 
}

greetNewJoiner.call(user1, <span class="hljs-string">"Frontend"</span> , <span class="hljs-string">"California"</span>)
<span class="hljs-comment">// "Hello Doe, John"</span>
<span class="hljs-comment">// "We are happy to welcome you to our California office and into Frontend team"</span>
greetNewJoiner.call(user2, <span class="hljs-string">"Devops"</span>, <span class="hljs-string">"California"</span>) 
<span class="hljs-comment">// "Hello Marshall, Alfred"</span>
<span class="hljs-comment">// "We are happy to welcome you to our California office and into Devops team"</span>

<span class="hljs-comment">// Apply example</span>
greetNewJoiner.apply(user2, [<span class="hljs-string">"Devops"</span>, <span class="hljs-string">"California"</span>]) 
<span class="hljs-comment">// "Hello Marshall, Alfred"</span>
<span class="hljs-comment">// "We are happy to welcome you to our California office and into Devops team"</span>
</code></pre><h3 id="bind">bind()</h3>
<p>Bind creates a new function and returns the function with newly bound <code>this</code> context.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">fName</span>: <span class="hljs-string">"Kevin"</span>,
  <span class="hljs-attr">sName</span>: <span class="hljs-string">"Edwards"</span>,
}

<span class="hljs-keyword">const</span> greetUser =  <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">`Welcome <span class="hljs-subst">${<span class="hljs-built_in">this</span>.sName}</span>, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.fName}</span>`</span>)
}

<span class="hljs-keyword">const</span> admin = {
  <span class="hljs-attr">fName</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">sName</span>: <span class="hljs-string">"Doe"</span>,
}

<span class="hljs-keyword">const</span> greetAdmin = greetUser.bind(admin)

greetAdmin()
<span class="hljs-comment">// "Welcome Doe, John"</span>
</code></pre>
<p>Most of the questions in interview will be around these three methods.</p>
<p>That's all for this article. Please let me know if I need to include anything else. </p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Free Resources for Web Developers]]></title><description><![CDATA[Hello!!!
I'm Tahir Ahmed, a frontend developer. This is my first ever article on any blogging platform.
In this article, I would like to let you all know about some of the free resources that are available for web developers for designing the website...]]></description><link>https://blog.tahirahmedt.com/free-resources-for-web-developers</link><guid isPermaLink="true">https://blog.tahirahmedt.com/free-resources-for-web-developers</guid><category><![CDATA[Web Development]]></category><category><![CDATA[HTML]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Tahir Ahmed]]></dc:creator><pubDate>Tue, 22 Dec 2020 10:15:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1608632085924/4zP5ep3Q3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello!!!</p>
<p>I'm Tahir Ahmed, a frontend developer. This is my first ever article on any blogging platform.</p>
<p>In this article, I would like to let you all know about some of the free resources that are available for web developers for designing the websites, using images, adding gradients, generating color palettes and many such things for websites.</p>
<p>These are the ones that I recommend personally as I use them in my work.</p>
<h3 id="free-images">Free Images</h3>
<p>Any good website has illustrations or images. It is not easy to find images that are not copyrighted. The following are some resources from where you can use images for free</p>
<p>1 <a target="_blank" href="https://unsplash.com/">Unsplash</a>:</p>
<p>Unsplash has tons of free images of all the things that you are looking for. They don't have any watermarks on them.</p>
<p>2 <a target="_blank" href="https://undraw.co/">Undraw</a>:</p>
<p>Undraw has free illustrations which you can download in any of the formats such as svg, png etc.</p>
<h3 id="gradients-and-colors">Gradients and colors</h3>
<p>Have you ever looked at a website and wished that you would also be able to create such good looking colorful websites? You can do it too.</p>
<p>1 <a target="_blank" href="https://cssgradient.io/">CSS Gradient</a>:</p>
<p>CSS Gradient provides an graphical user interface to create Gradients (both Linear and Radial) and allows you to choose from 256M colors. You get a chance to view how the gradient looks before you actually use it in your application.</p>
<p>2 <a target="_blank" href="https://coolors.co">Coolors</a>:</p>
<p>Coolors allows you to create a Color palette for your website. Press space bar, the next palette appears. If you like a color you can lock it and keep changing the other ones.</p>
<p>3 <a target="_blank" href="https://bennettfeely.com/clippy/">Clippy</a>:</p>
<p>Have you seen websites with skewed <code>div</code>s like the one below. These designs are called as skewed designs. We can achieve similar design by applying clip path to <code>::after</code> or <code>::before</code> pseudo elements. With Clippy we can create a clip path easily. It allows use to change shape of clip to such as Polygon, Cross or many such shapes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1608632075825/LtozNN94A.jpeg" alt="skewedwebsite.jpg" /></p>
<p>4 <a target="_blank" href="https://tailwindcss.com/docs/customizing-colors">Tailwind CSS Colors</a> </p>
<p>Tailwind developers have made a collection of colors that attract the human eye. </p>
<p>Thats all for this article.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item></channel></rss>