Shorthand for "function" keyword

T.J. Crowder tj.crowder at farsightsoftware.com
Fri Nov 10 13:38:04 UTC 2017


On Fri, Nov 10, 2017 at 1:11 PM, Laurentiu Taschina
<source.spider at gmail.com> wrote:
>
> I would like to propose the standard allow for shorthand form for
> the normal "function" keyword.
>
> ...
>
> Advantages & Motivation
>
> only regular functions can have names, but being so clunky people
> are discouraged from using the syntax in favor of short but
> anonymous arrow functions; this is detrimental for stack traces
> and debugging

That's a myth. The following function has the name `foo`, every bit as much
as `function foo() { ... }` would:

```js
const foo = () => {
    throw new Error();
};
console.log(foo.name); // "foo"
foo();                 // Stack trace will show the name "foo"
```

[Try it here][1] on any vaguely-recent version of Chrome or Firefox.

This was first defined in ES2015, the same spec that defined arrow
functions; search [the spec][2] for SetFunctionName to see all the various
places it applies. The short version is: If it's assigned to just about
anything but a property on a preexisting object and the name of the thing
it's being assigned to can reasonably be used as a name, that becomes the
name of the function. So `obj.foo = () => { }` doesn't assign a name (due
to [information leak concerns][3]), but assigning to a constant, variable,
property within an object initializer, parameter as default value, etc.,
all do on compliant implementations.

I think the only thing missing is hoisted declarations for non-`function`
functions (arrow functions have no declaration form), which doesn't
immediately seem like sufficient cause for a new keyword (but that's not my
call).

-- T.J. Crowder

[1]: https://jsfiddle.net/dfpdn0cj/
[2]: https://tc39.github.io/ecma262/
[3]:
https://esdiscuss.org/topic/name-anonymous-functions-on-property-assignments#content-20
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171110/c297402d/attachment.html>


More information about the es-discuss mailing list