<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: rohits1908</title>
    <description>The latest articles on DEV Community by rohits1908 (@rohitsharma08).</description>
    <link>https://dev.to/rohitsharma08</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1115928%2F91f34b27-0809-4eba-88b7-3bf1822a8c4c.png</url>
      <title>DEV Community: rohits1908</title>
      <link>https://dev.to/rohitsharma08</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rohitsharma08"/>
    <language>en</language>
    <item>
      <title>Navigating the 'this' Maze in Javascript - Part 1</title>
      <dc:creator>rohits1908</dc:creator>
      <pubDate>Sun, 09 Jul 2023 14:49:10 +0000</pubDate>
      <link>https://dev.to/rohitsharma08/navigating-the-this-maze-in-javascript-part-1-4lej</link>
      <guid>https://dev.to/rohitsharma08/navigating-the-this-maze-in-javascript-part-1-4lej</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;One of the most confusing mechanism in Javascript is understanding the &lt;code&gt;this&lt;/code&gt; keyword. It is a special identifier defined in the scope of every function, but what it refers to sometimes even may confuse even the seasoned JS developers.&lt;/p&gt;

&lt;p&gt;Let's try to simplify and understand the &lt;code&gt;this&lt;/code&gt; mechanism.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is &lt;code&gt;this&lt;/code&gt;?
&lt;/h2&gt;

&lt;p&gt;In simple words:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;this&lt;/code&gt; is the object executing in the current function&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Remember these simple thumb rules:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the executing function is a method an object then &lt;code&gt;this&lt;/code&gt; refers to that object itself (1)&lt;/li&gt;
&lt;li&gt;Otherwise if it is a regular javascript function i.e. it is not a member function then &lt;code&gt;this&lt;/code&gt; refers to the global object which is &lt;code&gt;window&lt;/code&gt; in browser and &lt;code&gt;global&lt;/code&gt; in Node (2)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's try to understand the above thumb rules through series of examples&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Example (1)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const song = {
    title: "'song title',"
    play() {
        console.log(this)
    }
}

song.stop = function() {
    console.log(this)
}

song.play()
song.stop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--q_SuvZrc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2azwvol9f47hngwical.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--q_SuvZrc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2azwvol9f47hngwical.jpg" alt="Output 1 - this within object" width="279" height="81"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have a &lt;code&gt;song&lt;/code&gt; object with &lt;code&gt;play()&lt;/code&gt; as method function. We have added another &lt;code&gt;stop()&lt;/code&gt; function to the same object.&lt;/li&gt;
&lt;li&gt;Since the &lt;code&gt;this&lt;/code&gt; is inside method function it points to the &lt;code&gt;song&lt;/code&gt; object.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Example (2)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function playSong() {
    console.log(this)
}

playSong()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--t6rWpkKG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/82osy316z60nrjtmm6ak.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--t6rWpkKG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/82osy316z60nrjtmm6ak.jpg" alt="Output 2 - this without object" width="634" height="24"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have a &lt;code&gt;playSong()&lt;/code&gt; function which doesn't links to any object.&lt;/li&gt;
&lt;li&gt;In this case &lt;code&gt;this&lt;/code&gt; links to the &lt;code&gt;window&lt;/code&gt; object in browser.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Example 3&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's Modify the above code to look something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Song(title) {
    this.title = title
    console.log(this)
}

const songObj = new Song('song title')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can you guess the output for above example?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rhKlF8Ni--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwad3dqcvf0l4xljfr67.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rhKlF8Ni--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwad3dqcvf0l4xljfr67.jpg" alt="Output 3 - this with new keyword" width="194" height="55"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have a &lt;code&gt;Song()&lt;/code&gt; function which doesn't belong any object in the initially but later we create a &lt;code&gt;songObj&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;songObj&lt;/code&gt; is initialised using a &lt;code&gt;new&lt;/code&gt; keyword which creates an empty object and then points &lt;code&gt;this&lt;/code&gt; to the &lt;code&gt;{}&lt;/code&gt; empty object.&lt;/li&gt;
&lt;li&gt;Finally we add the &lt;code&gt;title&lt;/code&gt; property to &lt;code&gt;this&lt;/code&gt; object.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Example 4&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's take a look at another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const song = {
    title: 'song title',
    comments: ['x', 'y', 'z'],
    showComments () {
        this.comments.forEach(function(comment){
            console.log(this.title, comment)
        })
    }
}

song.showComments()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--akCySybs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shh5s6lu8zp3ut273fm0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--akCySybs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shh5s6lu8zp3ut273fm0.jpg" alt="Output 4 - this in forEach loop in javascript" width="234" height="58"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is going on in the above example?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If you remove &lt;code&gt;title&lt;/code&gt; from above example in &lt;code&gt;console.log()&lt;/code&gt; you can see that the &lt;code&gt;this&lt;/code&gt; actually now points to the global (&lt;code&gt;window&lt;/code&gt;) object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;But we're inside the &lt;code&gt;song&lt;/code&gt; object shouldn't the &lt;code&gt;this&lt;/code&gt; point to &lt;code&gt;song&lt;/code&gt; object?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you look at the function inside the &lt;code&gt;forEach&lt;/code&gt; loop it is just a regular javascript function, it is not a method inside the &lt;code&gt;song&lt;/code&gt; object. The &lt;code&gt;song&lt;/code&gt; object only has one method &lt;code&gt;showComments()&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;So the &lt;code&gt;this&lt;/code&gt; inside the anonymous callback function inside &lt;code&gt;forEach&lt;/code&gt; loop holds context to the global object.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Now you must be wondering how can we solve this problem?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const song = {
    title: 'song title',
    comments: ['x', 'y', 'z'],
    showComments () {
        this.comments.forEach(function(comment){
            console.log(this.title, comment)
        }, this)
    }
}

song.showComments()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The second argument in the &lt;code&gt;forEach&lt;/code&gt; takes the context info, so when we call the &lt;code&gt;showComments()&lt;/code&gt; while passing &lt;code&gt;this&lt;/code&gt; as the context we're still in the execution context of &lt;code&gt;showComments()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Now when you run the above code look at output.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cUPUnCEG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ql2003i0opl01gfn6vom.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cUPUnCEG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ql2003i0opl01gfn6vom.jpg" alt="Output 4 - fixing this in forEach" width="245" height="58"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Now every function in javascript doesn't accept the context argument, so how can we change the &lt;code&gt;this&lt;/code&gt; context in javascript during runtime, will be covered in the next part (Part 2).&lt;/p&gt;

&lt;p&gt;Thank You for Reading. Happy Learning!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;: Mosh Hamedani - JavaScript Fundamentals&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
