ES6 Arrow functions
Arrow Functions is undoubtedly one of the most popular features of ES6. They introduced a new way of writing concise functions. They have two major benefits that most people will use them.
First, they provide a shorthand syntax for declaring functions and cutting down the overall amount of code that we need to write for a function. Next, they simplify the behavior of this keyword in JavaScript by keeping its context in the same scope as the function using it.
Let's understand the above-mentioned things in detail.
Let's take a look at a simple function and re-implement it as an arrow function.
- function sayHi(name){
- return "Hi, "+ name;
- }
- sayHi(Joey);
Here, we've written a function called sayHi.
When we pass a value like Joey for the name parameter, it will return Hi, Joey.
Let's create a new function using the arrow style called sayHi.
- const sayHi = (name) => {
- return "Hi, "+ name;
- };
First, we'll have to declare a variable to hold it, we'll use const instead of let since we don't expect that this function will change while it's in scope. Arrow functions are sometimes called fat arrow functions or lambda functions, but the official ES6 term is an arrow function.
You may notice that it doesn't look like we've shortened things much versus a regular function declaration. But if our function is a one-liner then we can omit the curly braces and the return keyword.
- const sayHiMiniVersion = name => "Hi, "+ name;
- const timesThree = number => number*3;
- const multiply = (x, y) => x*y;
A pivotal thing about arrow functions is how they work with the JavaScript keyword.
In traditional-style JavaScript functions, the keyword "this" references depend on how we've called the function. Sometimes keyword "this" references the containing function, sometimes "this" references the global namespace, sometimes "this" references the ajax call, and sometimes "this" references something else altogether. It's difficult to know in advance because it all depends on how the calling code was implemented.
Arrow functions are different because this always refers to the containing code. The fancy term for this is lexical binding.
Let's try to understand with an example

Join the conversation! Your thoughts help the community grow.