JavaScript and TypeScript course ยท Module 12: Functional Programming

What is Functional Programming?

7 min read ยท
In this lesson6

The morning report from the raptor enclosure says: 12 animals. The evening one, generated by the same function from the same data, says: 13. Nothing hatched, nothing escaped - some function quietly changed a shared counter. Bugs like this cannot be reproduced on demand, and functional programming pulls the ground out from under them.

Imagine a laboratory in Jurassic Park where every experiment on dinosaur DNA always produces the same result given the same input data. There are no side effects - no dinosaur escapes, no security system is accidentally disabled. This is exactly how functional programming (FP) works - it's a paradigm where code behaves like a controlled scientific experiment.

What You Will Learn

  • tell pure functions apart from impure ones,
  • process arrays of samples with map, filter and reduce,
  • assemble functions into processing lines with pipe and compose,
  • configure functions in stages and lock data away in closures,
  • walk the species tree with recursion and change data without mutation,
  • handle missing data and errors with Maybe and Either,
  • build a functional security reporting system for the park.

Functional vs Imperative Paradigm

In imperative programming, we tell the computer how to do something step by step. In functional programming, we describe what we want to achieve, using functions as the fundamental building blocks.

The task: pick the carnivores out of a list of species. First a classic loop, then the functional version:

// Imperative approach - step by step
const dinosaurs = ['T-Rex', 'Velociraptor', 'Triceratops', 'Stegosaurus'];
const carnivores = [];
for (let i = 0; i < dinosaurs.length; i++) {
  if (dinosaurs[i] === 'T-Rex' || dinosaurs[i] === 'Velociraptor') {
    carnivores.push(dinosaurs[i]);
  }
}

// Functional approach - declarative
const isCarnivore = (name) => ['T-Rex', 'Velociraptor'].includes(name);
const carnivoresFP = dinosaurs.filter(isCarnivore);

Both versions produce ['T-Rex', 'Velociraptor']. In the first one we look after the counter i, the loop condition and appending results with push ourselves. In the second we only name the rule: isCarnivore uses includes to check whether a name is on the list of carnivores, and we hand the walk through the array over to filter, which returns a new array with the matching elements. What did not change? The dinosaurs array stays untouched in both versions.

Pure Functions

A pure function is a controlled experiment - given the same input data, it always returns the same result and causes no side effects.

Rules of a Pure Function:

  1. Determinism - same input = same output, always
  2. No side effects - does not modify anything outside its scope

The first function below calculates a danger level from its three arguments alone. The second does something that looks innocent: along the way, it bumps a counter declared outside of it.

// PURE FUNCTION - always the same result
function calculateDangerLevel(weight, speed, aggression) {
  return (weight * 0.3) + (speed * 0.3) + (aggression * 0.4);
}

// The same function called 1000 times with the same arguments
// will always return the same result
calculateDangerLevel(8000, 40, 95); // always 2450
calculateDangerLevel(8000, 40, 95); // always 2450

// IMPURE FUNCTION - modifies external data
let totalDinosaurs = 0;
function addDinosaur(name) {
  totalDinosaurs++; // side effect - modifies external variable!
  return { name, id: totalDinosaurs };
}
// Each call produces a different result, even with the same argument
addDinosaur('Rex'); // { name: 'Rex', id: 1 }
addDinosaur('Rex'); // { name: 'Rex', id: 2 } - different result!

The call calculateDangerLevel(8000, 40, 95) is 2400 + 12 + 38, which makes 2450 - today, tomorrow and on the thousandth repetition. addDinosaur is different: the same argument 'Rex' gives two different results, because the function depends on the variable totalDinosaurs, which it changes itself. That is the mechanism behind the bug in the morning report.

A side effect is any change to the world outside the function: modifying an external variable or an object passed in, writing to the console, a request to a server, changing the page content. Determinism, in turn, is broken by any source of variability, such as randomness:

// Impure: a side effect in the form of a console entry
function logSample(id) {
  console.log('Sample:', id);
  return id;
}

// Impure: the result depends on chance, not on the arguments
function randomZone() {
  return Math.random() > 0.5 ? 'A' : 'B';
}

Neither of them touches the park's data, and yet both are impure: logSample leaves a trace in the console, and randomZone, with no arguments at all, returns 'A' one time and 'B' another. Any function that reads the time through Date.now() is impure in the same way.

Immutability

Immutability is the principle that once created, data is never changed. Instead of modifying an existing object, we create a new copy with changes. It's like creating a new DNA sequence instead of modifying an existing one - safer and more predictable.

Compare two ways of recording that Rex has been injured:

// MUTATION - dangerous (modifying the original object)
const dinosaur = { name: 'Rex', health: 100 };
dinosaur.health = 80; // The original object has been changed!

// IMMUTABILITY - safe (new object)
const dinosaurSafe = { name: 'Rex', health: 100 };
const injuredDinosaur = { ...dinosaurSafe, health: 80 };
// dinosaurSafe still has health: 100 (unchanged)
// injuredDinosaur has health: 80 (new object)

The spread operator (...) copies all fields into a new object, and health: 80 written after it overrides one field of the copy. Notice also that const did not protect the dinosaur object from being changed: it blocks reassigning the variable, not the contents of the object. We will come back to this difference in the lesson on immutability patterns.

Functions as First-Class Citizens

In JavaScript, functions are first-class citizens - you can assign them to variables, pass them as arguments, and return them from other functions.

First, the first two options: we store a function in a constant and then pass it to filter, the way a sample is passed between workstations:

// Function assigned to a variable
const classify = (dino) => dino.diet === 'carnivore' ? 'dangerous' : 'safe';

// Function as an argument
const dinosaurs = [
  { name: 'Rex', diet: 'carnivore' },
  { name: 'Brachio', diet: 'herbivore' },
];
const dangerous = dinosaurs.filter((dino) => classify(dino) === 'dangerous');

Assigning classify does not run anything - it is a recipe that filter will call for each dinosaur. Only Rex ends up in the dangerous array.

The third option is the most interesting, because a function can build and return a new function:

// Function returning a function
function createValidator(minWeight) {
  return (dino) => dino.weight >= minWeight;
}
const isHeavyDino = createValidator(5000);
isHeavyDino({ weight: 8000 }); // true
isHeavyDino({ weight: 200 });  // false

createValidator(5000) produces a ready-made validator that remembers the minWeight threshold, even though the factory call finished long ago. Functions that take or return other functions are called higher-order functions, and the mechanism for remembering variables is a closure - we will develop both topics in the coming lessons.

Why Bother?

You test a pure function without preparing the world around it: you pass arguments and compare the result - remember Jest from the previous location? You can also safely remember its result or chain it with other functions. You will not write a program entirely without side effects, though, because someone has to display the report. That is why I recommend Dr. Rex's rule to you: keep effects at the edges of the program (loading data at the start, console.log and saving at the end), and write the logic in the middle as pure functions.

In the editor below, change the arguments and check which functions behave like a controlled experiment.

Functional programming comes down to a single promise: the same input always yields the same result, no specimen is quietly altered behind your back, and functions travel through your code as freely as any other value in the laboratory.

Code for this lesson: index.js
// Functional programming - Introduction
console.log("=== Jurassic Park - Pure Function Laboratory ===\n");

// EXAMPLE 1: Pure vs impure function

// PURE FUNCTION - always the same result, no side effects
function calculateDangerLevel(weight, speed, aggression) {
  return (weight * 0.3) + (speed * 0.3) + (aggression * 0.4);
}

console.log("--- Pure functions ---");
console.log("T-Rex danger:", calculateDangerLevel(8000, 40, 95));
console.log("T-Rex danger:", calculateDangerLevel(8000, 40, 95));
console.log("Identical results! A pure function is deterministic.\n");

// IMPURE FUNCTION - side effects
let totalRegistered = 0;
function registerDinosaurImpure(name) {
  totalRegistered++; // Side effect!
  return { name, id: totalRegistered };
}

console.log("--- Impure example ---");
console.log("Rex:", registerDinosaurImpure("Rex"));
console.log("Rex:", registerDinosaurImpure("Rex"));
console.log("Different results! The function depends on external state.\n");

// EXAMPLE 2: Immutability
console.log("--- Immutability ---");
const dinosaur = { name: "Rex", health: 100 };
const injuredDino = { ...dinosaur, health: 80 };

console.log("Original:", dinosaur);
console.log("New object:", injuredDino);
console.log("Original unchanged:", dinosaur.health === 100);

// EXAMPLE 3: Functions as values
console.log("\n--- Functions as values ---");
const classify = (dino) => dino.diet === "carnivore" ? "dangerous" : "safe";

const dinos = [
  { name: "Rex", diet: "carnivore" },
  { name: "Brachio", diet: "herbivore" },
  { name: "Raptor", diet: "carnivore" },
];

const dangerous = dinos.filter((d) => classify(d) === "dangerous");
console.log("Dangerous:", dangerous.map((d) => d.name));

// EXAMPLE 4: A function returning a function
function createWeightFilter(minWeight) {
  return (dino) => dino.weight >= minWeight;
}

const isHeavy = createWeightFilter(5000);
console.log("\nIs Rex (8000kg) heavy?", isHeavy({ weight: 8000 }));
console.log("Is Raptor (150kg) heavy?", isHeavy({ weight: 150 }));

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which of the following functions is a pure function?

  1. QuestionPure Function

Useful articles