Frontend Development 15 min read

Pure Functions in JavaScript: Concepts, Benefits, and Practical Examples

This article explains the definition of pure functions in JavaScript, illustrates their input‑output behavior, side‑effects, composition, point‑free style, and monadic encapsulation, and demonstrates how writing pure functions improves readability, testability, and refactoring with concrete code examples.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Pure Functions in JavaScript: Concepts, Benefits, and Practical Examples

Introduction

As a developer with five years of JavaScript experience, I often wonder what the core of the language is; the answer is closures and asynchrony, which are perfectly tied together by functional programming.

Pure Function Definition

A function is pure if it satisfies two conditions:

Given the same arguments, it always returns the same result and does not depend on any external state.

It produces no observable side effects such as network requests, I/O, or data mutation.

Input & Output

In a pure function, identical inputs always yield identical outputs. JavaScript methods like slice are pure, while splice mutates the original array and is not.

var arr = [1,2,3,4,5];

arr.slice(0,3); // [1,2,3]
arr.slice(0,3); // [1,2,3]
arr.slice(0,3); // [1,2,3]
var arr = [1,2,3,4,5];

arr.splice(0,3); // [1,2,3]
arr.splice(0,3); // [4,5]
arr.splice(0,3); // []

Other mutating array methods ( pop() , push() , shift() , unshift() , reverse() , sort() , splice() ) also break purity.

Side Effects

Pure functions must not cause observable side effects. Typical side effects include mutable data, console logging, user input, DOM queries, HTTP requests, Math.random() , new Date() , file system access, and database writes.

Mutable data

Logging

User input

DOM queries

HTTP requests

Randomness

Current time

System state

File system changes

Database inserts

Examples of impure functions:

let num = 0
function sum(x,y){
  num = x + y
  return num
}
function sum(x,y){
  console.log(x,y)
  return x+y
}
function of(){
  return this._value
}
function getRandom(){
  return Math.random()
}
function sum(x,y){
  throw new Error()
  return x + y
}

Benefits of Pure Functions

Self‑Documentation

Pure functions have clear contracts: identical inputs produce identical outputs, making the code act as its own documentation.

Example of a non‑pure sign‑up flow:

var signUp = function(attrs){
  var user = saveUser(attrs);
  welcomeUser(user);
};

var saveUser = function(attrs){
  var user = Db.save(attrs);
  ...
};

var welcomeUser = function(user){
  Email(user, ...);
  ...
};

Pure version with explicit dependencies:

var signUp = function(Db, Email, attrs){
  return function(){
    let user = saveUser(Db, attrs);
    welcomeUser(Email, user);
  };
};

var saveUser = function(Db, attrs){
  ...
};

var welcomeUser = function(Email, user){
  ...
};

Function Composition

Combining pure functions yields another pure function. Example composition utility:

const componse = (...fns) => fns.reduceRight((pFn, cFn) => (...args) => cFn(pFn(...args)))
function hello(name){ return `HELLO ${name}` }
function connect(firstName, lastName){ return firstName + lastName; }
function toUpperCase(name){ return name.toUpperCase() }

const sayHello = componse(hello, toUpperCase, connect)
console.log(sayHello('juejin', 'anthony')) // HELLO JUEJINANTHONY

Reference Transparency

A function call can be replaced by its return value without changing program behavior. This property enables algebraic reasoning and code reduction.

Refactoring example using immutable data and pure helpers:

var Immutable = require('immutable');

var decrementHP = function(player){
  return player.set("hp", player.hp-1);
};

var isSameTeam = function(p1, p2){
  return p1.team === p2.team;
};

var punch = function(player, target){
  if(isSameTeam(player, target)){
    return target;
  } else {
    return decrementHP(target);
  }
};

var jobe = Immutable.Map({name:"Jobe", hp:20, team:"red"});
var michael = Immutable.Map({name:"Michael", hp:20, team:"green"});

punch(jobe, michael);

After inline substitution and removing dead branches, the function simplifies to:

var punch = function(player, target){
  return target.set("hp", target.hp-1);
};

Point‑Free (Tacit) Style

Removing unnecessary parameter‑argument mapping improves readability. Example:

function double(x){ return x * 2; }
[1,2,3,4,5].map(double); // [2,4,6,8,10]

Monad as a Wrapper for Impure Operations

Real‑world code often needs side effects (file I/O, logging, randomness). By wrapping such operations in a Monad, they become composable pure values until explicitly executed.

var fs = require("fs");

// Pure function returning a Monad that reads a file
var readFile = function(filename){
  const readFileFn = () => {
    return fs.readFileSync(filename, "utf-8");
  };
  return new Monad(readFileFn);
};

var print = function(x){
  const logFn = () => {
    console.log(x);
    return x;
  };
  return new Monad(logFn);
};

var tail = function(x){
  const tailFn = () => {
    return x[x.length - 1];
  };
  return new Monad(tailFn);
};

// Chain operations without executing side effects
const monad = readFile("./xxx.txt").bind(tail).bind(print);
// No side effects have occurred yet
monad.value(); // Executes the file read, extracts the last line, and prints it

Before calling monad.value() , the whole pipeline remains pure, guaranteeing no external impact.

Conclusion

Starting from pure functions, writing elegant JavaScript requires embracing purity, composing pure functions, using point‑free style, and leveraging monads to isolate inevitable side effects. Pure functions lead to clearer, more testable, and more maintainable code.

javascriptcode refactoringFunctional Programmingpure functionsMonads
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.