Chuyển đến nội dung chính
eLearner.app
Mô-đun 4 · Bài học 2 trong tổng số 414/32 trong khóa học~10 min
Bài học theo mô-đun (2/4)

Chức năng mũi tên

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

tập thể dục#js.m4.l2.e1
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#js.m4.l2.e2
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử