⚡ Arrow Functions in JavaScript
Arrow functions offer a shorter and more readable way to write functions. Let’s learn how they work, how they differ from traditional functions, and when to use them.
🔍 What Is an Arrow Function?
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7
📌 Syntax Variations
- No Parameters:
const greet = () => console.log("Hello");
- One Parameter:
const square = n => n * n;
- Multiple Parameters:
const multiply = (a, b) => a * b;
- Multiple Statements:
const fullName = (first, last) => {
return first + " " + last;
};
🧠 Arrow vs Regular Function this
const person = {
name: "Alice",
sayHello: function () {
setTimeout(() => {
console.log("Hello, " + this.name);
}, 1000);
}
};
person.sayHello(); // Uses 'this' from person object
✅ When to Use Arrow Functions
- For short functions
- For callbacks (map, filter, etc.)
- When you want lexical
this
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
⚠️ When NOT to Use
- In constructor functions
- When
this
needs to be dynamic (like in classes)
🧪 Try It Yourself – Live Arrow Function Playground
Type or paste an arrow function below and click “Run”
📌 Summary
- Arrow functions are shorter and more elegant
- No own
this
orarguments
- Great for modern JavaScript and React code
0 Comments