Javascript: Arrow function expression

Ravina Deogadkar - Sep 26 '20 - - Dev Community

Javascript being functional language comes handy with different ways to create a function. Here we are going to talk about arrow function expression. Arrow function expression is a better alternative to classical methods but comes with limitations. Let's look at example below.

//Traditional method
function addValue(a){
return a+5;
}

The traditional function defined above can be rewritten in the form of arrow function expression as below.

//Arrow function expression
(a) => {
return a+5;
}

As we can see our function accepts only one argument, we can omit argument brackets and function body has only single return statement, we can omit curly braces. We can optimize function as below.

//Arrow function expression
a => a+5;

All it becomes a one line code perhaps called as an arrow function expression. We can even pass multiple arguments to arrow function.

//Arrow function expression
(a,b) => {
return a+b;
}

To use arrow function as traditional function, we can do it as follows.

//Arrow function expression
var sum = (a,b) => {
return a+b;
}
console.log(sum());

Here we are assigning arrow function to a variable sum and then we are calling it just like a traditional function.

Limitation

  1. Javascript arrow function doesn't have binding to this or super and must not be used. In arrow function this refer to the scope in which they are defined.

  2. We cannot use arrow function as a constructor, means we cannot use new keyword along with arrow function.

  3. We can't use yield within it's body.

  4. We can't use arrow function along with bind, apply or callfunctions.

That's it! Despite its limitations there are lots of advantages of arrow function expression.

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .