Topic 14 of 37
Arrow Functions Syntax
Overview
Introduced in ES6, arrow functions provide a more concise syntax for writing function expressions. They are anonymous by default. Importantly, they do NOT have their own 'this' binding—they inherit 'this' from the parent scope (lexical scoping). This makes them incredibly useful for callbacks, especially in React.
Syntax
Arrow functions remove the need for the 'function' keyword. If you omit the curly braces, the expression is implicitly returned.
Concise Syntax
javascript
// Traditional Function Expression
const add = function(a, b) {
return a + b;
};
// Arrow Function
const addArrow = (a, b) => {
return a + b;
};
// Implicit Return (no braces, no 'return' keyword)
const addImplicit = (a, b) => a + b;
// Single parameter (parentheses are optional)
const square = x => x * x;Common Pitfalls
- Returning an object literal implicitly requires wrapping the object in parentheses: `const getObj = () => ({ id: 1 })`. Otherwise, the engine thinks the curly braces are a function block.
Interview Tips
- Arrow functions cannot be used as Constructors (you cannot call them with 'new').
- They do not have an 'arguments' object.
Real-World Example
Array methods like map, filter, and reduce are almost always written with arrow functions for brevity.
example
javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]