Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ECMAScript 6's function.name property

Quick question: what's the correct result for this code:

let f = function(){};
let n = f.name; //"" or "f"?

According to the compat table, n should have the value "f". However, the mozilla docs say that it should return an empty string. Which one is correct?

like image 226
Luis Abreu Avatar asked Mar 25 '26 07:03

Luis Abreu


2 Answers

Since ECMAScript 6 is currently in draft state, the answer below may become outdated sometime in the future.
That being said, referencing the spec draft:

Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name own property but inherit the name property of %FunctionPrototype%.

The ECMAScript 6 Wiki reads that

If no name can be statically determined, such as in the case of an unassigned anonymous function, then the empty string is used.

however,

Some functions are anonymous and have no name given as part of their static semantics. If the function is directly assigned to a LHS where a name is statically determinable then the LHS name is used.

Note that the claims made by the wiki aren't referenced (and can't directly be found) in the spec draft, but they're reasonable assumptions.

If we take those assumptions to be true, the result of your sample function call would be "f", since the anonymous function is assigned to a LHS.
Reading the name property of an unassigned anonymous function should return an empty string.

like image 83
Etheryte Avatar answered Mar 27 '26 19:03

Etheryte


It will return "f", in your example, as well as in other variations:

let f = function(){}
const f = function(){}
var f = function(){}
f = function(){}  // assignment
let f = () => {}
// etc.

The relevant bits in ES6 spec draft are all the occurrences of SetFunctionName. In the case of your example, see its invocation in Section 13.2.1.4. It applies only when the RHS syntactically is an anonymous function literal.

like image 39
Andreas Rossberg Avatar answered Mar 27 '26 20:03

Andreas Rossberg