Paradigms: objects, functions and types · Part 11 of 36

Functional programming: values in, values out

Intermediate 15 min

Pure functions, immutability, higher-order functions and composition, and how they compare with OOP.

What you will learn

  • You can write code with pure functions and immutable data.
  • You can use higher-order functions (map, filter, reduce) and closures.
  • You can compare functional and object-oriented designs for a task.

Before this: Object-oriented programming: classes and objects

The idea

Functional programming (FP) builds programs from pure functions that take values and return new values, without changing anything outside. Instead of "take this object and modify it step by step", you describe a pipeline: "the result is this transformation of that input".

Languages such as Haskell, Elm and Clojure are built around FP. JavaScript and Python are multi-paradigm: you can mix styles, and most modern code does.

A pipeline of glass tubes passing coloured liquid through filters

Immutability

In FP you avoid changing data in place. Instead of pushing onto a list, you create a new list:

const beds = ["north", "south"];
const more = [...beds, "east"];           // beds is unchanged
const renamed = beds.map((b) => b.toUpperCase());
const bed = { name: "north", area: 3.6 };
const bigger = { ...bed, area: 4.2 };      // new object, old one intact
beds = ("north", "south")                  # tuple: cannot change
more = beds + ("east",)
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Bed:
    name: str
    area: float
bigger = replace(Bed("north", 3.6), area=4.2)

Why bother? Data that never changes can be shared safely between parts of a program — and between threads (expert tier). Bugs where "something somewhere changed my list" disappear. Undo/redo becomes trivial: keep the old versions.

Functions as values

In both languages functions are first-class values: you can store them in variables, pass them as arguments and return them. A function that takes or returns functions is a higher-order function — map, filter and reduce are the famous ones.

const byArea = (a, b) => a.area - b.area;
const sorted = [...bedList].sort(byArea);
const total = bedList.map((b) => b.area).reduce((s, x) => s + x, 0);
from functools import reduce
total = reduce(lambda s, x: s + x, (b.area for b in bed_list), 0)
# More "Pythonic": total = sum(b.area for b in bed_list)

Closures

A function defined inside another function remembers the variables around it, even after the outer function has finished. That is a closure:

function makeCounter() {
  let n = 0;
  return () => ++n;
}
const next = makeCounter();
next(); next();   // 2
def make_counter():
    n = 0
    def next_():
        nonlocal n
        n += 1
        return n
    return next_

Closures let you build specialised functions ("a tax function for 20 %") and keep private state without classes.

Composition

Small functions combine into bigger ones: slugify = compose(lowercase, trim, replaceSpaces). Each piece is trivial to test, and the pipeline reads like a description of the task.

OOP or FP?

They are tools, not religions:

  • FP fits data transformations, calculations, compilers, anything "input → output". It is easy to test and to run in parallel.
  • OOP fits long-lived things with identity and changing state: UI widgets, devices, sessions.
  • Common modern style: a functional core (pure logic, immutable data) inside an imperative shell (the part that reads files, talks to the network, updates the screen). Many of the apps on this site work that way: a pure engine shared by the app, the tool pages and the API.

Try it: JavaScript sandbox

Write and run small JavaScript programs; the checker tells you when an exercise is solved.

Turn on JavaScript to use this lab. Worked example:

Exercise 11: without using a for loop, print the sum of the squares of the even numbers in [1, 2, 3, 4, 5, 6] (4 + 16 + 36 = 56). Use filter, map and reduce.

Key points

  • FP builds programs from pure functions and immutable data.
  • Copy instead of mutate: spread syntax, tuples, frozen dataclasses.
  • Functions are values: higher-order functions take or return functions (map, filter, reduce).
  • Closures remember the variables of the scope where they were created.
  • A functional core in an imperative shell combines the strengths of both styles.

Flashcards

Question: What is a higher-order function?
Answer: A function that takes another function as an argument or returns one.
Question: What is a closure?
Answer: A function that remembers the variables of the scope it was created in.
Question: Name one benefit of immutable data.
Answer: It can be shared safely (also between threads) and makes undo easy.
Question: What does "functional core, imperative shell" mean?
Answer: Pure logic in the middle, side effects (I/O, UI) at the edges.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. Which line creates a new array without changing the original arr?

    • [...arr, 4]
    • arr.push(4)
    • arr[3] = 4
    • arr.splice(0, 1)
    Show the answer

    [...arr, 4]

    Spread syntax builds a new array; push, assignment and splice mutate arr.

    Source: MDN, Spread syntax

  2. What does [1, 2, 3].map(x => x * 2).reduce((s, x) => s + x, 0) return?

    Show the answer

    12

    map gives [2, 4, 6]; their sum is 12.

    Source: MDN, Array.prototype.reduce()

  3. const next = makeCounter(); next(); next(); next(); — what does the last call return?

    • 3
    • 1
    • 0
    • undefined
    Show the answer

    3

    The closure keeps n between calls: 1, 2, 3.

    Source: MDN, Closures

  4. Which tasks fit a functional style especially well?

    • Turning a CSV file into a summary report
    • Computing a price from inputs
    • A long-lived game character with changing state
    • A compiler pass that rewrites a syntax tree
    Show the answer

    Turning a CSV file into a summary report; Computing a price from inputs; A compiler pass that rewrites a syntax tree

    Input → output transformations suit FP; long-lived state with identity is a typical OOP case.

    Source: Python Functional Programming HOWTO

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.