Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Pure Functions

Pure functions are predictable: same input, same output, no side effects.

They are the foundation of reliable and testable code.

Why We Need It

When functions are pure, debugging becomes easier because behavior is consistent.

They are also safer to reuse and refactor.

Syntax

function fn(input) { return output; }

Basic Example

1. Pure function

function add(a, b) {
  return a + b;
}

console.log(add(2, 3));

No external state, same output for same inputs.

Real World Example

2. Impure function

let total = 0;
function addToTotal(amount) {
  total += amount;
  return total;
}

This function changes external state, so it is impure.

Multiple Use Cases

Deterministic Output

A pure function always returns the same output for the same input.

It does not rely on or change external state.

No Side Effects

Pure functions do not modify global variables, DOM, or external data.

This makes them easy to test and reason about.

Why It Matters

Pure functions are predictable and safe to reuse.

They are ideal for calculations, transformations, and utilities.

More Examples

3. Pure transformation

function toUpper(words) {
  return words.map((w) => w.toUpperCase());
}

console.log(toUpper(["a", "b"]));

Input array is not modified, output is new.

4. Avoid side effects

function formatPrice(amount) {
  return "$" + amount.toFixed(2);
}

console.log(formatPrice(99));

Pure utility functions are easy to reuse.

Comparison

Without

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

With

function add(total, amount) {
  return total + amount;
}

Common Mistakes and Fixes

Mutating inputs

Return new values instead of modifying parameters.

Using global state

Pass all required data via parameters.

Hidden side effects

Avoid logging or IO in functions meant to be pure.

Interview Questions

What is a pure function?

It returns the same result for the same input and has no side effects.

Why are pure functions easier to test?

They do not depend on external state.

Give an example of a side effect.

Modifying a global variable or logging to the console.

Practice Problem

Practice: Write a pure function that converts Celsius to Fahrenheit.

// TODO: function toF(c)

One Possible Solution

function toF(c) {
  return (c * 9) / 5 + 32;
}

console.log(toF(0));

Frequently Asked Questions

What makes a function pure?

Same inputs produce same output and no side effects.

Are pure functions always better?

Not always, but they are easier to test and reuse.

Is console.log a side effect?

Yes, it interacts with external state.

Try It Yourself

Try calling the function multiple times with the same input.