Lambdas with Arrow Functions

Functions are used everywhere in JavaScript. A face-lift to make their syntax succinct, and consequently easier to use and understand, was long overdue.

JavaScript is, at its core, a functional programming language. It supports functions as first-class citizens, in that they are like any other type in the language. Functions can be assigned to variables, supplied as arguments to other functions, and be returned from functions just like we would any other type in JavaScript. JavaScript is also singlethreaded. Well-designed APIs and libraries that involve long-running operations work asynchronously, typically accepting a callback which is to be invoked when the (asynchronous) task is complete. These callbacks happen to be functions as well. Finally, the mechanism to define methods on objects also happen to be functions.

In this chapter we will get acclimated with a new syntax for function expressions, also referred to as “arrow” functions that was introduced in ES6. We will see how our code can be made eloquent with shorter syntax, thereby allowing us to express our intent clearly. Our discussion will include how arrow functions’ behaviors differ from regular functions, allowing us to discern when best to use arrow functions. By the end of this chapter, you will be raring to return to your codebase knowing that you can confidently eliminate any unnecessary verbosity, leaving behind, well ... let’s just call it poetry, shall we?

~

Raju Gandhi ⇒ GANDHI, Raju, 2019. Lambdas with Arrow Functions. In: GANDHI, Raju (ed.), JavaScript Next: Your Complete Guide to the New Features Introduced in JavaScript, Starting from ES6 to ES9. Online. Berkeley, CA: Apress. p. 13–26. [Accessed 10 May 2022]. ISBN 978-1-4842-5394-6.

There is a new way to define functions in JavaScript, known as the fat arrow. Fat arrows are intended to be used for quick anonymous functions, especially where you want to use the outer 'this' context. To help streamline this use case when you use them without a single expression instead of a block they implicitly return the value of that expression.