Arrow functions in 2 minutes

In this article I’ll be talking briefly about The relatively new JavaScript arrow functions introduced in ES2015(popularly known as ES6) and how to use them. This is a short guide on what arrow functions are , their syntax and how to use them, so let’s hop on in!

javascript functions

ES6 arrow functions provide you with an alternative way to write a shorter syntax compared to the traditional javascript function expression.

Here is a code snippet for a traditional JavaScript function that multiplies 2 numbers :

multiply = function(x,y) {
  return x * y;
}
console.log(multiply(12,2)); // 24

The following example uses an arrow function which is equivalent to the above multiply() function expression:

let multiply = (x,y) => x * y; console.log(multiply(12,2)); // 24;

you would already agree with me that arrow functions make the function declaration process more concise.

writing arrow functions

lets now see the structure of an arrow function.

let func = (arg1, arg2, ...argN) => expression

This creates a function func that accepts arguments arg1..argN, then evaluates the expression on the right side with their use and returns its result.

comparing again to the traditional javascript function:

let func = function(arg1, arg2, ...argN) {
  return expression;
};

we see certain differences:

  1. the arrow function gets rid of the function keyword declaration
  2. there is no need for the return keyword
  3. introduction of the => symbol between the argument and expression , hence the name "arrow" function.

rules of writing arrow functions

1.If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.

For example:

let double = n => n * 2;
alert( double(3) ); // 6

2.If there are no arguments, parentheses will be empty (but they should be present):

let sayHi = () => alert("Hello!");
sayHi();

these are just a few basic concepts to give an overview of what you can accomplish with arrow functions, they are already widely adopted and serve to be very useful in writing concise javascript code, i hope you're fortunate using them!