An arrow function is, at first glance, just a fancy way to create regular JavaScript functions (however, there are some surprises). Using arrow functions, you can create concise one-liner functions that actually work!
The following example demonstrates how to create an arrow function:
let circumference = (pi, r) => {
let ans = 2 * pi * r;
return ans;
}
let result = circumference(3.141592, 3);
console.log(result); // Outputs 18.849552
Here, circumference is a variable, referencing to the anonymous arrow function.
The previous code is similar to the following code in ES5:
var circumference = function(pi, r) {
var area = 2 * pi * r;
return area;
}
var result = circumference(3.141592, 3);
console.log(result); //Output 18.849552
If your function contains just a single statement (and you want to return the result of that statement), then you don't have to use the {} brackets to wrap the code. This makes it a one-liner. The following example demonstrates this:
let circumference = (pi, r) => 2 * pi * r;
let result = circumference(3.141592, 3);
console.log(result); //Output 18.849552
When {} brackets are not used then the value of the statement in the body is automatically returned. The preceding code is equivalent to the following:
let circumference = function(pi, r) { return 2 * pi * r; }
let result = circumference(3.14, 3);
console.log(result); //Output 18.84
Also, if there's only a single argument, you can omit the brackets to make the code even shorter. Consider the following example:
let areaOfSquare = side => side * side;
let result = areaOfSquare(10);
console.log(result); //Output 100
Since there is only one argument, side, we can omit the circular brackets for this.