You might have noticed function definitions with const or let alongside the function name, an arrow and then parameters enclosed in brackets. This is the new way of defining functions in JavaScript. Arrow functions provide us with an alternative way that writes shorter syntax compared to the traditional used function expression.
These are with very simple and concise syntax to create a function, and are often better than general Function Expressions.
They are called “arrow functions”, because of the arrow notation they have in their syntax.
const func_name = (arg1, arg2, ..., argN) => expression;
This creates a function func_name
that will accept arguments arg1..argN
, and then evaluate the expression on the right side using the arguments and returns a result.
There is another shorter version of this.
const func_name = function(arg1, arg2, ..., argN) {
return expression;
};
The following example defines a function expression using an arrow function that returns the product of two numbers.
const product = function (a, b) {
return a * b;
};
console.log(product(10, 20)); // 200
We can also use this with the block syntax as stated below.
const product = (a, b) => { return a * b; };
Benefits of using Arrow Functions
Arrow functions have many advantages as compared to normal functions.
- They reduces a lot of code and makes the code more readable.
- The syntax they use automatically binds “this” keyword to the surrounding code’s context.
- Writing the arrow => is more flexible as compared with the using the traditional used function keyword.