Codectionary / Developer documentation / JavaScript

Arrow Functions

Arrow functions provide a more concise syntax for writing function expressions in JavaScript. Introduced in ES6, they use the => syntax and have some important differences from regular functions, particularly in how they handle the "this" keyword. Arrow functions are especially useful for callbacks, array methods, and short inline functions.

Syntax

const functionName = (parameters) => { /* body */ }

Examples

Basic Syntax

Different ways to write arrow functions based on parameters and body length.

// No parameters
const greet = () => {
  console.log("Hello!");
};

// Single parameter (parentheses optional)
const square = x => x * x;
console.log(square(5)); // 25

// Multiple parameters
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7

// Multiple statements
const multiply = (a, b) => {
  const result = a * b;
  return result;
};

console.log(multiply(6, 7)); // 42

Array Methods

Using arrow functions with array methods for clean, readable code.

const numbers = [1, 2, 3, 4, 5];

// Map - transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Filter - select elements
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

// Reduce - accumulate values
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

// Chaining methods
const result = numbers
  .filter(n => n > 2)
  .map(n => n * 3)
  .reduce((acc, n) => acc + n, 0);

console.log(result); // 36

Object Methods

Returning objects from arrow functions requires parentheses.

// Return object literal
const createPerson = (name, age) => ({ name, age });

const person = createPerson("Alice", 25);
console.log(person); // { name: "Alice", age: 25 }

// Array of objects
const users = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 35 }
];

const names = users.map(user => user.name);
console.log(names); // ["John", "Jane", "Bob"]

const adults = users.filter(user => user.age >= 30);
console.log(adults);

Callbacks and Promises

Arrow functions shine in asynchronous code and event handlers.

// setTimeout callback
setTimeout(() => {
  console.log("Delayed message");
}, 1000);

// Event handler
document.querySelector("#myButton")?.addEventListener("click", (event) => {
  console.log("Button clicked!", event.target);
});

// Promises
fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

// Async/await
const fetchData = async () => {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
};

Best practices

  • Use arrow functions for short, simple operations and callbacks
  • Omit parentheses for single parameters, but always use them for clarity in complex cases
  • Remember that arrow functions don't have their own "this" - they inherit it from parent scope
  • Wrap object returns in parentheses: () => ({ key: value })
  • Don't use arrow functions for object methods if you need access to "this"
  • Prefer arrow functions in array methods (map, filter, reduce) for conciseness

Browser compatibility

chrome
Yes
firefox
Yes
safari
Yes
edge
Yes

These are the existing reference’s support labels, not tested minimum versions. Individual values and APIs can have different support. Check the linked specification before choosing a browser target.

ECMAScript specification

Specifications & further reading