Pure Functions in JavaScript
6 min read·Jan 1, 2025
A pure function is a deterministic function with no side effects.
This means that given the same input, it always produces the same result and does not modify its arguments, change the value of variables outside of its scope, or perform input/output operations.
Example
Let's consider this script, where the add function is a pure function as it solely uses its supplied arguments and doesn't call external code:
function add(a, b) {
return a + b;
}
console.log(add(1, 2));
console.log(add(1, 2));
Which will produce this output:
$ node pure_function.js
3
3
Example
Let's consider this script, where the increment function is not a pure function as it relies on the global counter variable, which produces a different result at each invocation.
let counter = 0;
function increment() {
counter = counter + 1;
return counter;
}
console.log(increment());
console.log(increment());
Which will produce this output:
$ node side_effect_function.js
1
2
Function composition
In functional programming, function composition refers to the action of combining (or chaining) multiple functions together — usually pure functions — where the result of one function is passed as an argument to another function, and so on.
f = (x) => g(h(x));
It allows developers to create data transformation or validation pipelines, while ensuring the integrity of the original data.
Furthermore, function composition usually helps to make the code more understandable and maintainable by breaking down complex logic into smaller functions, and reduce code duplication by reusing individual functions across different parts of the application.
Example
Let's consider this script, that implements a function that returns a pure function:
function createMultiplier(number) {
return function(multiplier) {
return number * multiplier;
}
}
const double = createMultiplier(2);
console.log(double(4));
const triple = createMultiplier(3);
console.log(triple(4));
When executed, it will:
-
Define a function named
createMultiplierthat takes as argument anumberparameter.- Return a pure anonymous function that returns the product of the
numberparameter and its ownmultiplierparameter.
- Return a pure anonymous function that returns the product of the
-
Execute the
createMultiplierfunction and store its returned function into thedoublevariable. -
Execute the
doublevariable as a function and output its return value. -
Execute the
createMultiplierfunction and store its returned function into thetriplevariable. -
Execute the
triplevariable as a function and output its return value.
Which will produce this output:
$ node create_multiplier.js
8
12
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery