Arrow Functions
Explore the syntax and behavior of ES6 arrow functions, including implicit returns, handling of the this keyword, and differences from traditional functions. Understand when to use arrow functions effectively and how they impact scope and arguments in your JavaScript code.
What is an arrow function?
ES6 introduced fat arrows (=>) as a way to declare functions.
This is how we would normally declare a function in ES5:
The new syntax with a fat arrow looks like this:
We can go further if we only have one parameter. We can drop the parentheses and write:
If we have no parameters at all, we need to write empty parenthesis like this:
Implicitly return
With arrow functions, we can skip the explicit return and return like this:
Look at a side by side comparison with an old ES5 Function:
Both functions achieve the same result, but the new syntax allows you to be more concise. Beware! Readability is more important than conciseness so you might want to write your function like this if you are working in a team and not everybody is totally up-to-date with ES6.
Let’s say we want to ...