Arrow Functions Flashcards
What is an Arrow Function.
It’s called “arrow functions”, because it looks like this:
let func = (arg1, arg2, …, argN) => expression;
What does an Arrow Function do?
1.) Accepts arguments arg1..argN, then evaluates the expression on the right side with their use and returns its result.
2.) If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
(E.G)
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }
alert( double(3) ); // 6
3.) If there are no arguments, parentheses are empty, but they must be present.
(e.g)
let sayHi = () => alert(“Hello!”);
What are Multiline Arrow Functions?
Sometimes we need a more complex function, with multiple expressions and statements. In that case, we can enclose them in curly braces. The major difference is that curly braces require a return within them to return a value (just like a regular function does).
(e.g)
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit “return”
};
alert( sum(1, 2) ); // 3