Arrow functions in JavaScript are another new feature released with ES6 with a lot of benefits to start using. Arrow functions are pretty commonplace now but might confuse some newer JavaScript developers, but they are much simpler and straight forward than they seem. The main benefit of a using arrow function is it makes it much easier to write concise and clear functioning a much smaller amount of code and is especially useful when writing a one-line function as it also has implicit returns. In short coming across an arrow function can be confusing as it might look like some kind of strange way of declaring an object, but it just takes the function key word out of declaring a function. Here’s how you declare a simple arrow function.
let sum = (a, b) => a + b;
This function simply adds two numbers together, to declare the same function in the non-arrow traditional form you’d have to write it like this.
function sum(a, b) {
return a + b;
}
As you can see even though this is an absurdly simple function the arrow function makes it much simpler and, in this case, much easier to understand. If you are not creating a one liner function you can obviously still make multi lined function with arrow functions. For instance if you are summing all the elements of an array.
Non-arrow way:
function sum(arr) {
let sum = 0;
arr.forEach (function (num) {
sum += num
});
return sum;
}
Arrow function way:
const sum = (arr) => {
let sum = 0
arr.forEach ((num) => {
sum += num
})
return sum
}
As you can see arrow functions can also be used for iterators (the forEach) and other built in functions. Another slightly different syntax of a arrow function is the single argument function I am personally not a huge fan as it doesn’t save much space and doesn’t make the function any clearer but here is a quick example.
const half = a => a/2;
As you can see this function takes half of whatever number is inputted and the only real difference is not putting parenthesis around the variable.
The key differences between traditional function and arrow functions is how they use ‘this’. In a traditional function this is bound to the object that called the function. On the other hand, arrow function ‘this’ is always represents the object that defines the arrow function, in the example above it would be the const sum declaration of the function. This can cause some unintended consequences but if you’d like to use this in a more traditional way you will have to use the .bind() method. The different uses of this and how and how and why they are designer a certain way are a bit complicated and can be their own blog post, here is a good one (link) I found that goes into a lot more detail on how bind works in arrow functions. I hope this brief overview of arrow functions was helpful, happy coding!