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

  1. Write a basic arrow function: javascript const add = (a, b) => a + b;
  2. Use parentheses for single parameters when destructuring or with no params: javascript const greet = () => 'Hello'; const double = n => n * 2;
  3. Use a block body for multiple statements: javascript const sum = (arr) => { let total = 0; arr.forEach(n => total += n); return total; };
  4. Remember this is 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 this to 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 }).
  • arguments object is not available; use rest parameters (...args).