Arrow Functions
Overview
Arrow functions, introduced in ES6, provide a shorter, cleaner syntax for writing function expressions.
However, they are not just syntactic sugar! Arrow functions fundamentally change how the this keyword works. Traditional functions bind their own this context depending on how they are called. Arrow functions do not have their own this. They inherit this from the parent scope (Lexical Scoping).
Syntax
// Traditional
const add = function(a, b) {
return a + b;
};
// Arrow Function
const addArrow = (a, b) => {
return a + b;
};
// Implicit Return (One-liner!)
// If you remove the {} braces, the 'return' is automatic
const addQuick = (a, b) => a + b;// If there is exactly ONE parameter, you can omit the parenthesis!
const square = num => num * num;Common Pitfalls
- Trying to return an object implicitly:
const getObj = () => { name: 'Kartik' }. This returnsundefined! The JS engine thinks the{}is a standard code block, not an object literal. You MUST wrap the object in parentheses to implicitly return it:const getObj = () => ({ name: 'Kartik' }). - Using arrow functions as methods inside an Object. Because they don't bind
this,this.nameinside an object's arrow function method will returnundefined.
Interview Questions
this binding?No. Arrow functions lexically bind this. They inherit the this value from the enclosing execution context (the scope they were defined in).
new keyword with an arrow function?No. Because arrow functions lack their own this context and lack a prototype property, they cannot be used as Constructor functions. new MyArrowFunc() throws an error.
Real-World Example
Writing hyper-clean array iterations in React JSX without bloating the render function.
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>Check Your Knowledge
Test your understanding of Arrow Functions with these quick questions.