<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gaurav Chawla on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Chawla on Medium]]></description>
        <link>https://medium.com/@gauravchawla1603?source=rss-efb0cf96dbfc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jCJa5Qm1cOGMtqFTFkINKw.png</url>
            <title>Stories by Gaurav Chawla on Medium</title>
            <link>https://medium.com/@gauravchawla1603?source=rss-efb0cf96dbfc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:21:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravchawla1603/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding “this” in Javascript]]></title>
            <link>https://medium.com/swlh/understanding-this-in-javascript-166164e7fa2b?source=rss-efb0cf96dbfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/166164e7fa2b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Gaurav Chawla]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 11:56:42 GMT</pubDate>
            <atom:updated>2020-09-24T22:05:27.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*zqK3GEcyQzZBdxiOTyScMw.jpeg" /></figure><h3>Introduction</h3><p>I guess this is the most confusing concept in javascript, <strong>how to find</strong>this (context) of a function. And the misconception is to look where the function is declared or defined. this is a binding made for each function invocation.</p><blockquote>To understand this binding, we have to understand the <strong>call-site</strong>: the location in code where a function is called (<strong>not where it&#39;s declared</strong>). We must inspect the call-site to answer the question: what&#39;s this a reference to?</blockquote><h3>How to figure out “this” using call-site?</h3><p>Now we understood that, this (context) is dependent on the call-site and to find out the context javascript has some <strong>rules</strong> to decide.</p><h4>Rule 1 — Default Binding</h4><pre>// function declaration<br>function foo() {<br>    console.log(this.a);<br>}</pre><pre>var a = 1;</pre><pre>// call-site<br>foo(); // 1<br></pre><p>The first rule which is most commonly used: <strong>standalone function invocation. </strong>We see that when foo() is called this.a is referring to global variable a <strong>Why? </strong>Because foo() is called with a plain, un-decorated function reference so this will refer to the global object.<br>And in case of <strong>strict mode, </strong>this<strong> </strong>will be undefined and the above scenario will throw a <strong>Reference Error.</strong></p><h4>Rule 2 — Implicit Binding</h4><pre>function foo() {<br>    console.log(this.a)<br>}</pre><pre>var a = 5;</pre><pre>var bar = {<br>    a: 1,<br>    foo: foo<br>}</pre><pre>//call-site<br>bar.foo(); // 1<br></pre><p>Second rule, here we are using a reference to call the function. In the above example if you see, the call-site <em>uses</em> the bar context to reference the function, so you <em>could</em> say that the bar object &quot;owns&quot; or &quot;contains&quot; the function reference at the time the function is called. So this will refer to object bar and output will be 1 .</p><h4>Rule 3 — Implicit Lost</h4><pre>function foo() {<br>    console.log(this.a)<br>}</pre><pre>var a = &quot;global&quot;;</pre><pre>var bar = {<br>    a: &quot;local&quot;,<br>    foo: foo<br>}</pre><pre>var wiz = bar.foo;</pre><pre>//call-site<br>wiz(); // global</pre><p>In this rule there is slight confusion that even though wiz is a reference to bar.foo infact, it is just another reference to foo itself. So as we discussed from the start this depends on the <strong>call-site</strong> only and in above case which is a plain, un-decorated call and thus the <strong><em>default binding</em></strong> applies.this.a is resulting in global .</p><h4>Rule 4 — Explicit Binding</h4><p>As you all are aware we can explicitly provide context to a function call using <strong>call</strong>, <strong>apply</strong> and <strong>bind</strong>.</p><pre>// function declaration<br>function foo() {<br>    console.log(this.a);<br>}</pre><pre>var obj = {<br>    a: &quot;Obj reference&quot;<br>};</pre><pre>foo.call(obj); // Obj reference</pre><p>In this rule, as we see the above case we are explicitly providing context for function foo using call method of functions. So this will refer to object obj as provided by call method and same applies for <strong>apply method </strong>also. But let’s take one example for <strong>bind</strong> to clear out confusions if any.</p><pre>function foo() {<br>    console.log(this.a);<br>}</pre><pre>var obj = {<br>    a: &quot;Obj reference&quot;<br>};</pre><pre>var bar = foo.bind(obj);<br>bar(); // Obj reference</pre><p>In this scenario, you will be tempted to consider it as default rule but it is different because we hard binded the context of function bar using bind and after that it will <strong>not depend on its call-site</strong> actually. That is the reason it is considered as a different rule.<strong>If you know above 4 rules you can easily figure out the context of a function invocation at anytime, anyplace in your code.</strong></p><h3>Arrow Functions/ Fat Arrow</h3><p>Now one more thing we all should know that <strong>breaks all the above rules</strong> and introduced in ES6, that are <strong>Arrow Functions a.k.a Fat Arrow.</strong></p><p>Arrow functions use context of its lexical scope. In simpler way, arrow-functions adopt the this binding from the enclosing (function or global) scope. Let’s the below example to clear out more -</p><pre>function foo() {<br>	// return an arrow function<br>	return (a) =&gt; {<br>		// `this` here is lexically adopted from `foo()`<br>		console.log( this.a );<br>	};<br>}<br><br>var obj1 = {<br>	a: 2<br>};<br><br>var obj2 = {<br>	a: 3<br>};<br><br>var bar = foo.call( obj1 );<br>bar.call( obj2 ); // 2, not 3!</pre><p>So when we wrote var bar = foo.call( obj1 ); , if you see the declaration of function foo() it doesn’t involve any arrow function so according to the standard 4 rules we calledfoo with reference to object obj1 and its return function is assigned to bar . <br>Now the next line bar.call( obj2 ); even though we are calling the return function with reference to object obj2 but it is declared as an arrow function so it will use the context of function foo which we set to object obj1 i.e Output will be <strong>2 not 3.</strong></p><h3>Summary</h3><ol><li>To find out context orthis of a function invocation is dependent on its <strong>call-site (location where function is called).</strong></li><li>To figure out context from call-site, we have some standard rules which we discussed.</li><li>Arrow Functions doesn’t follow any standard rule,they adopt the this binding from the enclosing (function or global) scope.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=166164e7fa2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-this-in-javascript-166164e7fa2b">Understanding “this” in Javascript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Javascript: Closures]]></title>
            <link>https://medium.com/@gauravchawla1603/understanding-javascript-closures-3c332b44e936?source=rss-efb0cf96dbfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c332b44e936</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gaurav Chawla]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 21:06:34 GMT</pubDate>
            <atom:updated>2020-09-08T15:32:27.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*zqK3GEcyQzZBdxiOTyScMw.jpeg" /></figure><h3>Introduction</h3><p>Undoubtedly every javascript developer is using closure in his/her day to day life at work and failed to answer the same question once in a lifetime.</p><blockquote><em>“Closure is all around you in JavaScript, you just have to recognise and embrace it.” — Kyle Simpson</em></blockquote><h3>What are Closures?</h3><p>Closure is when a function is able to remember &amp; access its lexical scope even when the function is executed outside its lexical scope. Closure is a behavior of functions &amp; only functions. Closure doesn’t apply on objects, nor classes.</p><blockquote>A <strong>lexical scope</strong> in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.</blockquote><p>Let&#39;s take an example for better understanding -</p><pre>function eventCounter() {<br>    var count = 0;<br>    return function() {<br>        count++;<br>        console.log(count);<br>    }<br>}</pre><pre>var counter = eventCounter();</pre><p>For the basic understanding eventCounter function contains a private variable count and returns a function. Now let’s see what happens when we call the counter function again and again.</p><blockquote><em>Want to read this story later? Save it in </em><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=blog&amp;utm_campaign=noteworthy&amp;utm_content=eid7"><em>Journal</em></a><em>.</em></blockquote><pre>counter();<br>// 1</pre><p>When counter function is invoked for the first time we all know that it will print 1 in console.</p><pre>counter();<br>// 2</pre><p>Now the question arises here, when we are invoking the counter function for the second time it will console 2 not 1. <strong>Why?</strong><br>The reason behind this is <strong>closure</strong>, even if we are calling the counter function outside it has access to the lexical scope(basically in the outer scope of the returned function) variable count in eventCounter function through <strong>closure scope</strong>. So when we called the counter function first time its value is incremented to 1 and now when we are accessing the same variable in the 2nd call which is now incremented from 1 to 2.</p><h3>Benefits of Closures?</h3><ol><li>Able to access the private variable &amp; functions using closures.</li><li>Maintain state between each function call.</li></ol><p>In the example, the private variable count can be accessed in the return function scope and its value was maintained in the second call</p><h3>Why Closures?</h3><p>Imagine you have a button on a page that when clicked, should retrieve and send some data via an Ajax request. Without using a closure:</p><pre>var APIendpoints = {<br>    studentIDs:<br>        &quot;https://some.api/register-students&quot;,<br>    // ..<br>};<br><br>var data = {<br>    studentIDs: [ 14, 73, 112, 6 ],<br>    // ..<br>};<br><br>function makeRequest(evt) {<br>    var btn = evt.target;<br>    var recordKind = btn.dataset.kind;<br>    ajax(<br>        APIendpoints[recordKind],<br>        data[recordKind]<br>    );<br>}<br><br>// &lt;button data-kind=&quot;studentIDs&quot;&gt;<br>//    Register Students<br>// &lt;/button&gt;<br>btn.addEventListener(&quot;click&quot;,makeRequest);</pre><p>The makeRequest(..) utility only receives an evt object from a click event. From there, it has to retrieve the data-kind (accessed as btn.dataset.kind) attribute from the target button element, and use that value to look up both a URL for the API endpoint as well as what data should be included in the Ajax request.</p><p>This works OK, but it’s unfortunate (inefficient, more confusing) that the event handler has to read a DOM attribute each time it’s fired. Why couldn’t an event handler <em>remember</em> this value? Let’s try using closure to improve the code:</p><pre>var APIendpoints = {<br>    studentIDs:<br>        &quot;https://some.api/register-students&quot;,<br>    // ..<br>};<br><br>var data = {<br>    studentIDs: [ 14, 73, 112, 6 ],<br>    // ..<br>};<br><br>function setupButtonHandler(btn) {<br>    var recordKind = btn.dataset.kind;<br><br>    btn.addEventListener(<br>        &quot;click&quot;,<br>        function makeRequest(evt){<br>            ajax(<br>                APIendpoints[recordKind],<br>                data[recordKind]<br>            );<br>        }<br>    );<br>}<br><br>// &lt;button data-kind=&quot;studentIDs&quot;&gt;<br>//    Register Students<br>// &lt;/button&gt;<br><br>setupButtonHandler(btn);</pre><p>With the setupButtonHandler(..) approach, the data-kind (accessed as btn.dataset.kind)attribute is retrieved once and assigned to the recordKind variable at initial setup. recordKind is then closed over by the inner makeRequest(..) click handler, and its value is used on each event firing to look up the URL and data that should be sent.</p><p>I hope this article provided a better understanding and clarity on the topic and JavaScript.</p><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c332b44e936" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>