How to use arrow functions in JavaScript
· Category: JavaScript
Short answer
Arrow functions provide a concise syntax, implicit return for single expressions, and lexical this binding, making them ideal for callbacks and functional patterns.
Steps
- Write a basic arrow function:
javascript const add = (a, b) => a + b; - Use parentheses for single parameters when destructuring or with no params:
javascript const greet = () => 'Hello'; const double = n => n * 2; - Use a block body for multiple statements:
javascript const sum = (arr) => { let total = 0; arr.forEach(n => total += n); return total; }; - Remember
thisis lexical and inherited from the enclosing scope:javascript const obj = { value: 10, getValue: () => this.value // `this` is from outer scope, not obj };
Tips
- Do not use arrow functions as methods if you need
thisto refer to the object. - Arrow functions cannot be used as constructors and have no
prototype.
Common issues
- Returning an object literal requires parentheses:
() => ({ a: 1 }). argumentsobject is not available; use rest parameters(...args).