JS Arrow Functions
In this page:
const functionName = (parameters) => expression;
const functionName = (parameters) => {
// body
return value;
};
Arrow Function Syntax
An arrow function replaces the function keyword with =>, placed after the parameter list, and for a single expression, the curly braces and return keyword can both be omitted entirely.
उदाहरण: Arrow Function Syntax
const add = (a, b) => a + b;
console.log(add(2, 3));
Implicit Return
When an arrow function's body is a single expression, you can omit both the curly braces and the return keyword, JavaScript automatically returns the expression's result.
उदाहरण: Implicit Return
const square = n => n * n; // implicit return, no braces needed
console.log(square(5));
Arrow Functions in Array Methods
Arrow functions are extremely common as short, inline callbacks passed to array methods like map, filter, and forEach, keeping the code compact and readable.
उदाहरण: Arrow Functions in Array Methods
const nums = [1, 2, 3];
console.log(nums.map(n => n * 2));
this in Arrow Functions
Unlike regular functions, arrow functions do not have their own this, they inherit this from the enclosing scope where the arrow function was defined, which can be either helpful or surprising depending on context.
उदाहरण: this in Arrow Functions
const obj = {
value: 42,
regular: function () {
const arrow = () => console.log(this.value); // inherits this from regular()
arrow();
},
};
obj.regular();
When NOT to Use Arrow Functions
Arrow functions are best avoided as object methods that need this, and cannot be used as constructor functions with new, regular function declarations remain the right choice in these specific cases.
उदाहरण: When NOT to Use Arrow Functions
const obj = {
value: 42,
// Avoid: arrow function as a method, 'this' won't refer to obj
broken: () => console.log(this),
};
obj.broken(); // this is NOT obj
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic