DEV Community

Cover image for The "this" confusion in JS: function vs arrow
Balaji Chennupati
Balaji Chennupati

Posted on

The "this" confusion in JS: function vs arrow

Hey there, Good to see you back again!, In this blog I would like to clear a common confusion for many js beginners, the "this" confusion while using it b/w arrow and normal functions.

Standard function's perspective of this keyword

"this" is a keyword in js which is normally used to refer the object that we are currently working with or in terms of methods "this" refers to the object in which the method is located at.

const obj={
  name:"bj",
  info:function(){
        console.log(this.name);
       }
}
Enter fullscreen mode Exit fullscreen mode

The above is a simple object representation in js with a name attribute and an info method now when we call the obj.info() what do you think it console logs?

bj
Enter fullscreen mode Exit fullscreen mode

Yep! it prints the name of obj. But if write the same code outside of the object in the global execution context then "this " references to window object which is the initial global object in browser by default and it may vary from run time to run time.

So by this I would like to very much say that the default global object for any standard function is global object, but if working with any object then it becomes the this reference.

Arrow functions perspective of this keyword

In terms of arrow functions things slightly change, Let's write the same object above but in terms of arrow function this time and see what it outputs.

const obj={
  name:"bj",
  info:()=>{
        console.log(this.name);
       }
}
Enter fullscreen mode Exit fullscreen mode

Now what do you think happens when i do the method call obj.info() well you might think we just changed the syntax but working is same, Well I am sorry to say but you are wrong mate. The standard functions in js by default have their own scope whereas arrow functions highly depend on lexical scope (simply scope around it) since the global scope refers to window object and window object does not have a name property we get the value undefined as output.

undefined
Enter fullscreen mode Exit fullscreen mode

So by the end of this blog, What I would like to share with you is try to use this keyword only in standard functions and constructors, try not to use this in ES6 star boys (arrow functions 😉) and try to understand how they work.

That's it for this blog, Catch you in the next one till then Adios.

Top comments (0)