Arrow Functions in JavaScript
Arrow functions, introduced in ES6 (ECMAScript 2015), provide a shorter syntax for writing functions. They are especially useful in functional programming and callbacks.
📝 Basic Syntax
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
🎯 Features
- Simpler syntax, especially for small functions
- Does not bind its own
this
value - Best used for callbacks or inline functions
💡 One-Liner Arrow Functions
const square = x => x * x;
console.log(square(5)); // Output: 25
📦 Multiple Lines & Return
const greet = name => {
const message = "Hello, " + name;
return message;
};
console.log(greet("Alice"));
⚠️ Arrow Functions and this
Unlike regular functions, arrow functions do not have their own this
. They inherit it from the surrounding lexical scope.
const person = {
name: "Bob",
greet: function() {
setTimeout(() => {
console.log("Hi, I'm " + this.name);
}, 1000);
}
};
person.greet(); // Output: "Hi, I'm Bob"
💡 Use arrow functions to preserve
this
in methods or inside timeouts and event handlers.