0

Why does the following code result in undefined?

I've tried different syntax but none of them have worked.

const robot = {
  model: '1E78V2',
  energyLevel: 100,
  provideInfo: () => {
    `I am ${this.model} and my current energy level is ${this.energyLevel}.`
  }
};
console.log(robot.provideInfo())

I expected to print the values of model & energyLevel.

Hid
  • 533
  • 6
  • 18
  • 2
    Do not use an arrow function when you want to capture the calling context of the function when invoked – CertainPerformance Jul 26 '19 at 14:58
  • 2
    You forgot to return the string. – Seblor Jul 26 '19 at 14:58
  • 1
    Add a `return` or remove the curly braces `provideInfo: () => 'I am ${this.model} and my current energy level is ${this.energyLevel}.'` – Damien Legros Jul 26 '19 at 14:59
  • Yes this still is not a Perl/Ruby language we need declare return directly as a many braces – oklas Jul 26 '19 at 15:00
  • I disagree with the marked duplicate, the way to do what you're looking for is with ES5's `get` features. See this answer: https://stackoverflow.com/a/4616262/5471957 – SpeedOfRound Jul 26 '19 at 15:41
  • @SpeedOfRound Shorhand getter method syntax would be effectively the same as using a full-fledged `function`, but the issue has nothing to do with getting/setting. Unless a getter is actually useful, better to just use a `function` or *non-getter* method instead of the arrow function (as the linked canonical question describes) – CertainPerformance Jul 26 '19 at 22:17

0 Answers0