Arrow functions provide a shorter syntax for writing functions and handle this differently from regular functions.

1. Basic Syntax

Traditional function

function add(a, b) {
return a + b;
}

Arrow function

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

2. Implicit Return (One-Line Functions)

If the function body has one expression, you can omit {} and return.

const add = (a, b) => a + b;

console.log(add(2, 3)); // 5

3. Single Parameter Shortcut

If there is only one parameter, parentheses are optional.

const square = x => x * x;
console.log(square(4)); // 16

❌ Not allowed for zero or multiple parameters.

const sayHi = () => "Hi!";

4. Returning Objects

Wrap the object in parentheses to avoid confusion with {}.

const createUser = (name, age) => ({
name,
age
});console.log(createUser("Zaman", 25));

5. Arrow Functions with Arrays

Very common with array methods:

const numbers = [1, 2, 3, 4];

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]

Other examples:

numbers.filter(n => n % 2 === 0);
numbers.reduce((sum, n) => sum + n, 0);

6. Arrow Functions and this (MOST IMPORTANT)

Arrow functions do not have their own this.
They inherit this from the surrounding scope (lexical this).

❌ Regular function issue

const user = {
name: "Zaman",
sayHello: function () {
setTimeout(function () {
console.log(this.name); // undefined
}, 1000);
}
};

✅ Arrow function solution

const user = {
name: "Zaman",
sayHello: function () {
setTimeout(() => {
console.log(this.name); // Zaman
}, 1000);
}
};

✔ Arrow functions fix this problems in callbacks.

7. Arrow Functions vs Regular Functions

Feature Regular Function Arrow Function
Syntax Longer Short
this Dynamic Lexical
arguments Available ❌ Not available
new keyword ✔ Yes ❌ No
Hoisting ✔ Yes ❌ No
Best for Methods, constructors Callbacks, array methods

8. Arrow Functions and arguments

Arrow functions do not have arguments.
Use rest parameters instead.

const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3)); // 6

9. Arrow Functions Cannot Be Constructors

const Person = (name) => {
this.name = name;
};const p = new Person("Zaman"); // ❌ TypeError

✔ Use regular functions or classes for constructors.

10. Arrow Functions in Event Listeners (Warning)

Arrow functions inherit this, so they may not work as expected in event handlers.

button.addEventListener("click", () => {
console.log(this); // window, not button
});

button.addEventListener("click", function () {
console.log(this); // button
});

11. Arrow Functions with Default Parameters

const greet = (name = "Guest") => `Hello ${name}`;
console.log(greet());
console.log(greet("Zaman"));

12. Real-World Use Cases

API calls

fetch(url)
.then(res => res.json())
.then(data => console.log(data));

Sorting

users.sort((a, b) => a.age - b.age);

Timers

setTimeout(() => console.log("Done"), 1000);

Categorized in:

Javascript ES6,