Arrow Functions1 min read

What is arrow function?

In short, it’s a shorthand for writing function in which “this” input returns “this” output. Additional to already stated, we can leave return keyword but only in certain cases.
Benefits of using arrow functions is definetly shorter syntax ie.
If we have no input we write syntax like this:

[syntax_prettify]var calculate = () => 2+5; // logs "7"[/syntax_prettify]

If we have one argument, we can leave parentheses i.e.:

[syntax_prettify linenums="linenums"]var calculate = count => count * 2;
console.log(calculate(2)) // logs "4"[/syntax_prettify]

If we have multiple arguments we use parentheses:

[syntax_prettify linenums="linenums"]var calculate = (val1, val2) => val1 * val2;
console.log(calculate(2,4)) // logs "8"[/syntax_prettify]

If we dont have a single expression we can specify a block and in that case we need to use return keyword.

[syntax_prettify linenums="linenums"]var calcualte = (val1, val2) => { 
var result = (val1 / 100) + (val2 * 10);
return result;
}[/syntax_prettify]

SUMMARY:

  • Real purpose of arrow functions is to handle this keyword (sets the context to the code we are running and not context of a function)
  • When using arrow functions we are not able to use bind/call/apply to change this context
  • it is not possible to set arrow (=>) in a new line! Everything must be written in single line
(Visited 11 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *