DEV Community

Cover image for Arrow function and this
Bishwas Shrestha
Bishwas Shrestha

Posted on

Arrow function and this

What would be the result of this foo.baz()??

const foo = {
  bar: 10,
  baz: () => console.log(this.bar),
};


foo.baz();

Enter fullscreen mode Exit fullscreen mode

This function looks like it should work but if you run this, the result will be “undefined”. Why so?
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.
In order to fix this issue we either use foo.bar or change a code a little and use regular function expression like so

 baz: function () {
    console.log(this.bar);
  },

Enter fullscreen mode Exit fullscreen mode

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 .

 baz: () => console.log(foo.bar),

Enter fullscreen mode Exit fullscreen mode

Now the output will be correctly 10.

Top comments (0)