Skip to main content
eLearner.app
Module 4 · Lesson 2 of 414/32 in the course~10 min
Module lessons (2/4)

Arrow function

Arrow functions are a more compact syntax for writing functions. Ideal for callbacks and short functions.

Basic syntax

JS
// 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:

JS
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:

JS
const descrivi = (n) => {
  const parita = n % 2 === 0 ? 'pari' : 'dispari';
  return `${n} è ${parita}`;
};

One parameter: optional parentheses

JS
const triplo = (n) => n * 3;
const triplo2 = (n) => n * 3; // this is fine too

With zero or two+ parameters, parentheses are mandatory:

JS
const ora = () => Date.now();
const min = (a, b) => (a < b ? a : b);

Try it

Exercise#js.m4.l2.e1
Attempts: 0Loading…

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).

Loading editor…
Show hint

const square = (n) => n * n;

Solution available after 3 attempts

Review exercise

Exercise#js.m4.l2.e2
Attempts: 0Loading…

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.

Loading editor…
Show hint

Use the body with braces when you have more than one expression.

Solution available after 3 attempts