Pure Functions in JavaScript

JavaScript·2 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:

pure_function.js
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.js33

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.