मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 4 · पाठ 2 का 4पाठ्यक्रम में 14/32~10 min
मॉड्यूल पाठ (2/4)

तीर फ़ंक्शन

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

व्यायाम#js.m4.l2.e1
प्रयास: 0लोड हो रहा है...

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

संपादक लोड हो रहा है...
संकेत दिखाएँ

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

3 प्रयासों के बाद समाधान उपलब्ध है

Review exercise

व्यायाम#js.m4.l2.e2
प्रयास: 0लोड हो रहा है...

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.

संपादक लोड हो रहा है...
संकेत दिखाएँ

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

3 प्रयासों के बाद समाधान उपलब्ध है