ES6 introduced arrow function syntax. Arrow functions remove the need to type out the keyword function every time you need to create a function.
To make an arrow function, we name it a variable. After the parameters, we add the arrow sign.
const add = (num1, num2) => {
return num1 + num2;
}
console.log(add(3,4)); // 7
is similar to:
function add(num1, num2) {
return num1 + num2;
}
console.log(add(3,4)); // 7
We can shorten the arrow function above as well.
const add = (num1, num2) => num1 + num2;
console.log(add(3,4)); // 7
Rules
// Zero parameters
const functionName = () => {};
// 1 parameter
const functionName = (para1) => {};
// 2 parameters
const functionName = (para1, para2) => {};
// Single-line block
const multiNumbers = (number) => number * number;
// Multi-line block
const multiNumbers = (number) => {
const multi = number * number;
return multi;
};