Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
Arrow functions are another way to declare functions.
// using function keyword function name() { return "Mary" } // using arrow function name = () => {
return "Mary"
}
If the function has only one statement, and the function returns a value, we can remove the curly brackets and the return keyword, as shown below:
const name = () => "Mary"
Note that, if we include curly brackets (i.e. the function is in a block), then we must also include the return keyword, as shown below:
const name = () => {return "Mary"}
If a function has only one parameter, we can remove the round brackets
/* With round brackets */ const square = (number) => number * number /* Without round brackets */ const square = number => number * number
An arrow function cannot contain a line break between its parameters (i.e. the round brackets) and its arrow.
/* Syntax error */ const result = () => 1 /* This is allowed */ const result = () => 1
Search online and research why we should not replace every normal function with an arrow functions. Then:
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.