Arrow Function use cases

Arrow Function use cases

Arrow functions are functions defined by the arrow =>.

The arrow makes code more readable by opting out of the function, returning syntax and reading the same way the function executes.

Arrows are shorthand function expressions and are syntactically similar to the related feature in C#, Java and CoffeeScript. It supports block statements and an expression that returns the value of an expression.

We cannot use the Arrow function as a constructor and it doesn’t have this, arguments and super.

The first part of the LHS of the assignment statement is the argument that is given to the function. If it’s a single function, you do not need another syntax. The next part is the arrow and the expression that would be returned.

The function is equivalent to;

Three ways to write Arrow function

  • By getting rid of the keyword function

  • We can remove the parenthesis if the function takes a single argument

  • The return statement and curly braces can be omitted if the body of the function is a single expression.

Code Samples of the three scenarios

By getting rid of the keyword function

We can remove the parenthesis if the function takes a single argument

The return statement and curly braces can be omitted if the body of the function is a single expression.

Why did they introduce Arrow functions? The introduction of Arrow functions was influenced by two factors

  • Shorter functions

  • Non-binding of ‘this.

SHORTER FUNCTIONS

Arrow functions work in a way that assumes anything after the symbol should be returned. So in this case, a+b will be returned. Both functions work exactly the same way, one is shorter and readable while the other is the normal version.

NON-BINDING OF ‘this’

With regular functions, the value of this is set based on how the function is called. With arrow functions, the value of this is based on functions surrounding the context. This means that the value of this inside an arrow function is the same the value of this outside the function.

Arrow functions work best when binding this to the context. It is often used in writing methods like map, reduce, filter and other array methods.

Arrow functions do not have their own this but they inherit it from its parent scope, in this case, the global one, even when we add "use strict"to our code, nothing will happen as it will give the same result since the scope comes from the parent one.