Module lessons (2/4)
Arrow function
Arrow functions are a more compact syntax for writing functions. Ideal for callbacks and short functions.
Basic syntax
// classic function
const somma = function (a, b) {
return a + b;
};
// equivalent arrow
const somma2 = (a, b) => {
return a + b;
};
// arrow with implicit return (concise body, no braces)
const somma3 = (a, b) => a + b;The three forms are equivalent. The third is the most "JavaScript-y".
When you can omit braces and return
If the body is a single expression:
const quadrato = (n) => n * n;
const isAdult = (eta) => eta >= 18;
const saluto = (nome) => `Ciao, ${nome}!`;If instead you need multiple statements, you need braces and an explicit return:
const descrivi = (n) => {
const parita = n % 2 === 0 ? 'pari' : 'dispari';
return `${n} è ${parita}`;
};One parameter: optional parentheses
const triplo = (n) => n * 3;
const triplo2 = (n) => n * 3; // this is fine tooWith zero or two+ parameters, parentheses are mandatory:
const ora = () => Date.now();
const min = (a, b) => (a < b ? a : b);Try it
Rewrite this function as an arrow function with implicit return: `function square(n) { return n * n; }`. Assign it to the const `square` and call it with 5 (expected 25).
Show hint
const square = (n) => n * n;
Solution available after 3 attempts
Review exercise
Define an arrow function `describe(n)` that returns the string `<n> è pari` if n is even, otherwise `<n> è dispari`. Call it with 7 as the last expression.
Show hint
Use the body with braces when you have more than one expression.
Solution available after 3 attempts