0

So, I'm using freecodecamp and it says that the following function is anonymous:

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

console.log(myFunc.name);

Well, how come it's anonymous if its name is clearly "myFunc"?

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 6
    The value of the named variable is an anonymous function. The function itself isn't named. It's just _referenced_ by the variable. – isherwood Dec 10 '21 at 18:59
  • 3
    That function is a named function. freecodecamp is incorrect. See [this answer](https://stackoverflow.com/a/37488652/215552) to [How do I write a named arrow function in ES2015?](https://stackoverflow.com/q/27977525/215552) – Heretic Monkey Dec 10 '21 at 19:04
  • Look here https://www.geeksforgeeks.org/javascript-anonymous-functions/ Arrow functions are anonymous always. – Flagmans Dec 10 '21 at 19:06
  • @isherwood That duplicate says nothing about arrow functions, just normal functions, and talks more about IIFEs than anything else. – Heretic Monkey Dec 10 '21 at 19:08
  • Fair enough, but I don't see how the fact that it's an arrow function is relevant. It's a function assigned to a variable. That duplicate covers the situation pretty well. – isherwood Dec 10 '21 at 19:10
  • I believe freecodecamp is probably expecting something like -> `const myFunc = function myFunc() {}`, unfortunately like mentioned you won't be able to use an arrow function here.. – Keith Dec 10 '21 at 19:29
  • `const myFunc = () => {};` is evaluated using [NamedEvaluation](//tc39.es/ecma262/#sec-runtime-semantics-namedevaluation) and the name `myFunc` is inferred. `myFunc.name === "myFunc"`. This function is not anonymous. Anonymous functions are often conflated with function expressions. – Sebastian Simon Dec 10 '21 at 20:05

1 Answers1

0

You are setting myFunc to reference an anonymous function. myFunc has a name, the anonymous function it references does not.

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

// This returns myFunc name
console.log(myFunc.name);

// This returns anonymous function's name which is blank
console.log(
(() => {
  const myVar = "value";
  return myVar;
}).name
);
Daniel Lord
  • 754
  • 5
  • 18
  • This is wrong. In JS, you cannot get the name of a variable binding, bindings are not objects. The function object does have a name. The lower example is a different function object which doesn’t have a name. – Sebastian Simon Dec 10 '21 at 20:11