Skip to content

Prefer arrow functions #23

Open
Open
@jhnns

Description

Over the past years, my personal preference on functions vs. arrow functions has shifted towards arrow functions. I used to be against arrow functions as a general replacement as they behave different than regular function. Typical arguments against arrow functions in general were:

  1. They don't provide arguments
  2. this is derived from the upper scope
  3. They are not callable via new
  4. They don't have a prototype
  5. They are not hoisted, but are only available after evaluation
  6. They appeared as anonymous function in stack traces (.name was undefined)

But now I've changed my mind:

  1. With rest parameters, arrow functions can have arguments. Rest parameters are better because they are actual arrays. And in general, I think that all these arguments and rest parameters tricks can be replaced with regular array arguments which are more explicit and expressive anyway.

  2. I never use this in regular functions. Functions that use this should be part of a class where you can use method shorthands without the function keyword. A function that uses this and that is not part of a class should rather accept an explicit argument than an implicit this (we already enforce this with no-invalid-this).

  3. This is a good feature. If a function should be callable with new, it should be a class

  4. Same as above

  5. This is never a real issue. If it is, it can be replaced with simpler and more explicit code. Not true. This may become an issue when evaluating modules that are part of a cyclic dependency graph.

  6. This is not true anymore. JavaScript engines derive the function name from the variable name:

bildschirmfoto 2018-03-31 um 16 19 50


Benefits of preferring arrow functions:

  • Not accidentally callable with new (already mentioned)
  • They discourage strange usage of this (already mentioned)
  • Unified function style (= no special rules that arrow functions are only appropriate in certain scenarios)
  • Shorter one line functions (no return) which are very common in functional programming patterns like Redux' action creators (see also Allow one line arrow functions #22)

The two last arguments are the most important ones for me that motivated me to change the rule. What do you think about it?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions