DevPath · Learn to code ESPTEN

Functional programming

Pure functions and immutability

Pure functions

A pure function follows two rules:

  1. Determinism: with the same arguments, it always returns the same result.
  2. No side effects: it does not modify anything outside itself (external variables, the DOM, the array it receives...).
// Pure: it only depends on its arguments
function add(a, b) {
  return a + b;
}

// Impure: it depends on something external and modifies it
let total = 0;
function accumulate(n) {
  total += n; // side effect
}

Pure functions are easy to test, reason about and reuse, because they keep no hidden state and hold no surprises.

Immutability

Instead of modifying data, functional programming prefers to create new copies with the changes applied. That way no one is affected by unexpected modifications:

const numbers = [1, 2, 3];

// Mutate (avoid it in functional style):
numbers.push(4);

// Immutable: create a new array
const extended = [...numbers, 4];

For objects you use the spread the same way:

const user = { name: "Ann", age: 30 };
const older = { ...user, age: 31 }; // copy with one change

Examples

Update an object without mutating it

const user = { name: "Ann", age: 30 };
const updated = { ...user, age: 31 };
console.log(user.age);    // 30 (untouched)
console.log(updated.age); // 31
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Higher-order functions and map/filter/reduce →