Member-only story
Arrow function syntax introduces a compact yet powerful way to write JavaScript functions. Removing verbosity around binding context, arguments, and returns, arrows bring ubiquitous lambdas to modern JavaScript.
In this article we’ll break down various flavors of arrow functions and when to leverage their capabilities.
Arrow Function Basics
The basics involve converting function expressions:
// Expression
const add = function(a, b) {
return a + b;
};
// Arrow
const add = (a, b) => {
return a + b;
};
Just switch function keyword for fat arrow => !
Implicit vs Explicit Returns
Arrow bodies containing single expressions automatically return results:
const double = n => n * 2;
console.log(double(8)); // 16
You can disable implicit returns using block body syntax:
const randInt = upper => {
return Math.floor(Math.random() * upper);
}
This provides control for more complex logic flows.