<?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: Bishwas Shrestha</title>
    <description>The latest articles on DEV Community by Bishwas Shrestha (@bishwas).</description>
    <link>https://dev.to/bishwas</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%2F1861540%2F09f77a67-32e7-429e-9d39-58b5c2934a7b.jpg</url>
      <title>DEV Community: Bishwas Shrestha</title>
      <link>https://dev.to/bishwas</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/bishwas"/>
    <language>en</language>
    <item>
      <title>Arrow function and this</title>
      <dc:creator>Bishwas Shrestha</dc:creator>
      <pubDate>Tue, 30 Jul 2024 11:33:33 +0000</pubDate>
      <link>https://dev.to/bishwas/arrow-function-and-this-b6n</link>
      <guid>https://dev.to/bishwas/arrow-function-and-this-b6n</guid>
      <description>&lt;p&gt;What would be the result of this foo.baz()??&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const foo = {
  bar: 10,
  baz: () =&amp;gt; console.log(this.bar),
};


foo.baz();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function looks like it should work but if you run this, the result will be “undefined”. Why so? &lt;br&gt;
In JavaScript, when you use an arrow function, the function console.log(this.bar) will look for a global variable, because “this” keyword is not bound to the surrounding object but a global object (window) in the browser or node.js environment. &lt;br&gt;
In order to fix this issue we either use foo.bar or change a code a little and use regular function expression like so&lt;br&gt;
&lt;/p&gt;

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or if we have to use an arrow function, instead of calling a local variable as this.bar, we can use object name and call foo.bar like so .&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; baz: () =&amp;gt; console.log(foo.bar),

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the output will be correctly 10. &lt;/p&gt;

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