Arrow Functions in ES6

Arrow Functions in ES6

·

3 min read

Today, we'll learn about Arrow functions, which is one of ES6's most intriguing features. It is a simpler and less time-consuming approach to writing functions. To make it easier for you to grasp, the entire code is broken down into smaller chunks. So, let's get started learning about this functionality.

Let's see if we can learn from this simple example. Consider the following scenario: We have a five-element array. Let's call our array numbers and use the term var to assign 5 numbers to it.

var numbers=[1,2,3,4,5]

Assume that each element in the numbers array must be cubed. So, let's build a function that will cube the numbers.

var numbers = [1,2,3,4,5];

function cube(x) {
  return x * x * x;
}

To get the result, we'll use our map function for simplicity's sake and assign a new variable to the output ,lets say result, so that we can get the desired result in the output.

var numbers = [1,2,3,4,5];

function cube(x) {
  return x * x * x;
}
var result = numbers.map(cube);
console.log(result);

In console, we have the output as:

[1,8,27,64,125]

We obtain the same effect if we copy the entire cube function and replace it with cube and remove the function name "cube."

var numbers = [1,2,3,4,5];

var result = numbers.map(function (x) {
  return x * x * x;
});

This was how a typical function would appear. Let's study Fat Arrow now so we can take this even further.

It even allows us to remove the word ”function” and replace it with “=>”

var numbers = [1,2,3,4,5];

var result = numbers.map((x) => {
  return x * x * x;
});

But be careful with writing this symbol. If space is detected between “=” and “>”the function wont work and you will end up getting an error. Now, there is even more simplicity for the functions that involves only or function with only a single parameter, function allows us to take one step further and even remove the curly braces and delete the keyword return.

var numbers = [1,2,3,4,5];

var result = numbers.map(x => x * x * x);
console.log(result);

Pros and Cons

A good programmer always tries to convert the entire program into minimum line of codes,and thus save time.But,with great power comes great responsibility.Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live. A good piece of code is written in such a way that even non-programmers can understand the rationale. However, for those who are new to coding, the arrow function makes it difficult to understand what is going on in the code. You can choose this type of simplified syntax depending on your project and use case, as well as your team.