-2

Does anyone know why the function without the arrow is showing the name value, but if use arrow function is showing the message undefined ?

Without the arrow function:

 const test = {
    prop: 42,
    name: "Leo",
    func: function(){
         return this.name
     },
   };

  console.log(test.func());

With the arrow function:

 const test = {
    prop: 42,
    name: "Leo",
    func: function() => this.name,
   };

  console.log(test.func());

Here is showing the message: undefined

  • 2
    Check the declaration of arrow function. @Spectric 's answer will be solve your issue. – Batuhan Sep 24 '21 at 21:25
  • Because arrow functions [don't have a `function` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Mike 'Pomax' Kamermans Sep 24 '21 at 21:27
  • [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/q/34361379) | [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/q/31095710) – VLAZ Sep 24 '21 at 21:44

1 Answers1

4

That is not how you declare an arrow function.

Remove the function part:

const test = {
  prop: 42,
  name: "Leo",
  func: () => this.name,
};

console.log(test.func());
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Spectric
  • 30,714
  • 6
  • 20
  • 43