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"?

7
  • 6
    The value of the named variable is an anonymous function. The function itself isn't named. It's just referenced by the variable. Commented Dec 10, 2021 at 18:59
  • 3
    That function is a named function. freecodecamp is incorrect. See this answer to How do I write a named arrow function in ES2015? Commented Dec 10, 2021 at 19:04
  • Look here geeksforgeeks.org/javascript-anonymous-functions Arrow functions are anonymous always. Commented Dec 10, 2021 at 19:06
  • @isherwood That duplicate says nothing about arrow functions, just normal functions, and talks more about IIFEs than anything else. Commented Dec 10, 2021 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. Commented Dec 10, 2021 at 19:10

1 Answer 1

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
);

Sign up to request clarification or add additional context in comments.

1 Comment

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.