JavaScript — Prerequisites for Functional Programming: Pure Functions

Keerthana
2 min readApr 14, 2022

An article for Mid level JavaScript Developers.
This is part of a series “JavaScript — Prerequisites for Functional Programming”

Series “JavaScript — Prerequisites for Functional Programming”

Functional Programming is the process of building software by following a certain rules. One of which is discussed in this article.

Use Pure functions instead of shared state & side effects

A pure function is a function that has the following properties:

Same input -> Same output
Should not depend on external mutable state
Should not cause side effect ie should not alter external state

Example of Impure Function

addToCart() mutates existing cart. It mutates the original data.
cart is received as parameter and the same gets modified.

In this code timing and order of execution impacts the result.

const addToCart = (cart, item, quantity) => {
cart.items.push({ item, quantity });
return cart;
};

Example of Pure function

addToCart() returns a new cart. It does not mutate the original data.
newCart is updated and returned. Parameter is not altered.

In this code timing and order of execution won’t affect result.

const addToCart = (cart, item, quantity) => {
const newCart = lodash.cloneDeep(cart); // Or 'Object.assign()'
newCart.items.push({ item, quantity });
return newCart;
};

Pure function avoids Side effects.

What is meant by causing Side Effect ?

When we change the state visible outside apart from return value, we are causing a side effect.
Ex: Modifying external scope like global var, state, writing in screen, console, file, etc, calling external functions causing side effects.

Problem with Shared State and causing Side Effects?

When a variable in shared scope or passed as param, functions that act on them are time dependent and dependent on order of execution. We will need to know history every shared state this function use or affects.

If we avoid shared state , Timing and order of execution won’t affect result.
Pure function avoids Shared State. This simplifies changes and refactoring.

Other Topics in this Series

JavaScript - Prerequisites for Functional Programming

5 stories

Pure functions
Function Composition
Higher-Order Functions
Currying
Declarative code
Data Immutability

--

--