Labs ICT
โญ Pro Login

Arrow Functions

Arrow Function Syntax

Arrow functions provide a shorter syntax compared to function expressions.

const add = (a, b) => {
  return a + b;
};

console.log(add(3, 4)); // 7
Try it Yourself โ†’

Implicit Return

With a single expression body, the return keyword and curly braces can be omitted.

const multiply = (a, b) => a * b;
const square = n => n * n;

console.log(multiply(4, 5)); // 20
console.log(square(6));      // 36

Single Parameter

With exactly one parameter, the parentheses can be omitted.

const double = n => n * 2;
const isEven = n => n % 2 === 0;

console.log(double(7));  // 14
console.log(isEven(10)); // true

No Parameters

For zero parameters, empty parentheses are required.

const greet = () => console.log("Hello!");
const getRandom = () => Math.random();

greet();          // Hello!
console.log(getRandom());

Returning Object Literals

Wrap the object in parentheses to distinguish it from a function body.

const createPerson = (name, age) => ({ name, age });

console.log(createPerson("Alice", 30));
// { name: "Alice", age: 30 }

Arrow Functions and this Binding

Arrow functions inherit this from their surrounding scope. They do not have their own this.

const counter = {
  count: 0,
  start() {
    setInterval(() => {
      this.count++;
      console.log(this.count);
    }, 1000);
  }
};

// counter.start() increments count correctly

Arrow Functions as Callbacks

Arrow functions shine as concise callbacks for array methods.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((a, b) => a + b, 0);

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens);   // [2, 4]
console.log(sum);     // 15

๐Ÿงช Quick Quiz

What is an arrow function?