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:

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

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

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

If we have multiple arguments we use parentheses:

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

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

var calcualte = (val1, val2) => { 
var result = (val1 / 100) + (val2 * 10);
return result;
}

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

Leave a Reply

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