CodeBlanks Logo Icon CodeBlanks

Pure functions

JavaScript course · Advanced · Lesson 54/100

Learn pure functions with no side effects that return the same output for the same input.

Pure functions

A pure function always returns the same output for the same input and never changes the outside world. It has no side effects: it does not write files, log to the screen, or mutate a global variable.

const add = (a, b) => a + b;

This function is pure because it only uses a and b and returns a new value. The input (2, 3) always yields 5. This property is called being deterministic, and it makes testing easy.

Side effects

A side effect is any observable change a function makes in the outside world. Mutating a global variable, logging to the screen, pushing to an array, or sending a network request are all side effects.

let total = 0;
function add(n) {
  total += n;
}

add is not pure because it mutates total. The same input can give different results because the answer depends on how many times it was called. Pure functions remove this ambiguity and make code easier to read.

Exercise Write a pure tax function

Write a pure arrow function named tax that takes a price parameter and multiplies it by the tax rate. Then call console.log(tax(100)) to log the result.

Show example solution
const tax = (price) => price * 1.2;
console.log(tax(100));

Test yourself

  1. Which one is a pure function?

    • let total = 0; function add(n) { total += n; }
    • function roll() { return Math.random(); }
    • const double = (n) => n * 2;
    • function log(msg) { console.log(msg); }
    Show answer

    const double = (n) => n * 2; — Correct! double only uses n and returns a new value; it does not touch external state.

  2. Complete a pure double function

    const double = (n) => ____;
    Show answer
    const double = (n) => n * 2;
  3. Match the pure function concepts

    pure function
    same input, same output
    side effect
    changes external state
    deterministic
    no randomness

All lessons in Advanced