When to Use Arrow Functions

There are pros and cons of using arrow functions instead of regular or anonymous functions. We discussed the benefits and limitations of arrow functions throughout this chapter. Let’s wrap up this discussion with the answer to the question: when should we consider using arrow functions?

Here are some recommendations that will help you make the right choice:

  • Don’t use arrow functions to define methods of a class, in an object literal, or through Object.prototype. The major hiccup here is the lexical scoping of this. If the method were defined using an arrow function, when the method is called, this will not refer to instance on which the method is called.

  • Avoid multiline arrow functions as arguments to functions—see Multiline Arrow Functions.

  • Use arrow functions if the function is a short one-liner. The reduced noise of arrow functions shines here.

  • When registering event handlers, don’t use arrow functions if this needs dynamic scoping instead of lexical scoping. But if you want lexical scoping instead of dynamic scoping for this, then arrow functions are a great choice.

  • Use single-line arrow functions as arguments to functions. The readability of code isn’t lost, especially if we break the lines and indent on each argument.

Follow these recommendations only when doing so will result in semantically correct code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset