What are arrow functions and when should I use them?
Asked on Jul 08, 2024
Answer
Arrow functions are a concise way to write functions in JavaScript, introduced in ES6. They are particularly useful for maintaining the lexical scope of "this" and for writing shorter function expressions.
// Traditional function expression
const add = function(a, b) {
return a + b;
};
// Arrow function
const addArrow = (a, b) => a + b;
Additional Comment:
✅ Answered with JavaScript best practices.- Arrow functions do not have their own "this" context; they inherit "this" from the parent scope.
- They are ideal for non-method functions and callbacks, such as in array methods like "map", "filter", and "reduce".
- They cannot be used as constructors and do not have a "prototype" property.
- Use arrow functions for cleaner and more readable code when the function body is simple.
Recommended Links:
← Back to All Questions