0

I'm running this code:

const myobj ={
mynum: ()=>{console.log("1")},
}
console.log(myobj.mynum())

It returns: 1 undefined

Where is "undefined" comes from? What's the main purpose to create a method like that? Is it even a method?

Panda
  • 1
  • 1
  • 4
    you're not returning anything. See this: https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions – WillardSolutions Aug 27 '18 at 19:07
  • No, [an arrow function is never a "method"](https://stackoverflow.com/q/34361379/1048572). "*Shorthand method definition*" does refer to [this syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions). – Bergi Aug 27 '18 at 19:23

1 Answers1

2

The undefined comes from the fact that the function doesn't return anything. Take for example

() => 3

That function will return a 3, notice that there isn't any {} around the function, and thus the last value evaluated will be returned.

Then take for instance this function:

() => { return 3; }

That will also return a 3 because we have explicitly added a return statement.

In your case you would need to add an explicit return statement if you want to use the {} braces, however console.log also returns undefined, so in your case either way would produce undefined as a result.

Asleepace
  • 3,466
  • 2
  • 23
  • 36
  • @RyanB true but that isn't necessarily part of the method declaration, rather it gets evaluated as a math expression, so the function still has the form `()=>3` for example `()=>(5-2)` – Asleepace Aug 27 '18 at 19:28