Arrow Functions

Arrow Functions

Arrow Functions in JavaScript

Arrow functions (=>) provide a shorter syntax for writing functions and behave differently from regular functions in terms of this.

šŸ”¹ Basic Syntax

const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8

✔ No need for the function keyword.
✔ Implicit return when there's only one expression.

šŸ”¹ When to Use Arrow Functions

1️⃣ Single Parameter (No Parentheses Needed)

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

✔ Parentheses are optional if there's only one parameter.

2️⃣ No Parameters (Requires Empty Parentheses)

const greet = () => "Hello, world!"; console.log(greet()); // Output: "Hello, world!"

3️⃣ Multi-line Function (Requires {} and return)

const multiply = (a, b) => { let result = a * b; return result; }; console.log(multiply(4, 5)); // Output: 20

Explicit return needed when using {}.

šŸ”¹ this in Arrow Functions

Unlike regular functions, arrow functions do not have their own this. Instead, they inherit this from their surrounding scope.

🟢 Example: Arrow Function and this

const person = { name: "Alice", greet: function() { setTimeout(() => { console.log(`Hello, ${this.name}!`); }, 1000); } }; person.greet(); // Output: "Hello, Alice!" (Correct)

✔ The arrow function inherits this from person.

⚠️ Regular Function vs Arrow Function

const person2 = { name: "Bob", greet: function() { setTimeout(function() { console.log(`Hello, ${this.name}!`); }, 1000); } }; person2.greet(); // Output: "Hello, undefined!" ❌

❌ Regular functions have their own this, so it refers to window (or undefined in strict mode).

šŸ”¹ Arrow Functions Can’t Be Used For

1️⃣ this-dependent Methods

const user = { name: "Charlie", sayHi: () => console.log(`Hi, ${this.name}`) }; user.sayHi(); // Output: "Hi, undefined" ❌

❌ Arrow functions don’t bind this, so this.name is undefined.

2️⃣ arguments Object (Not Available in Arrow Functions)

const sum = () => console.log(arguments); sum(1, 2, 3); // ❌ Error: arguments is not defined

✔ Use rest parameters instead:

const sum = (...args) => console.log(args); sum(1, 2, 3); // ✅ Output: [1, 2, 3]

3️⃣ Constructors (new Keyword Not Allowed)

const Person = (name) => { this.name = name; }; const p = new Person("Eve"); // ❌ Error: Person is not a constructor

✔ Use regular functions for constructors.

šŸŽÆ Summary

Shorter syntax than regular functions.
Implicit return when using a single expression.
Does not have this, arguments, or new.
Useful for callbacks, but not for methods or constructors.

šŸš€ Arrow functions make JavaScript cleaner and more readable! Let me know if you have any questions. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close