JavaScript Pure Functions and Side Effects

Menasria Hafidh
Nov 5 · 4 min read

Wondered what developers mean by the terms Pure Functions or Side Effects? And wonder why are they prevalent in the JavaScript ecosystem and pretty important to understand?

In this article, I’m going to walk you through these terms of Pure Functions and Side Effects by defining what they are and why they’re important to understand using code block examples. By the end of this article, you should be able to tell the difference between a regular Function and a Pure Function. On top of that, you should understand what Side Effects are and why you should avoid producing them in many different situations.

Let’s enjoy and learn:

Pure Functions

A function in JavaScript that’s considered to be a Pure Function has to have the following two properties:

  • Giving the same input always return the same output.
  • The function doesn’t produce any Side Effects.

Later in this article, we’ll take a closer look at what Side Effects but first let’s look at the first property:

Pure Functions have one-to-one mapping or connections between its inputs and its outputs and this means for every unique input there’s a unique corresponding output. To further understand what this looks like let’s look at the following clear block:

const customSalutation = (name) => {
return `Hey ${name}`;
}

The function customSalutation takes the name as an argument and returns out my custom salutation, the great thing about this function is that the output is easy to predict for, for the same name you give it you get the same returned greeting you expect.

If we create here constant called salutaion where I call customSalutation and passing my own name and then I print out my greeting constant and I get Hey Hafid as an output.

const customSalutation = (name) => {
return `Hey ${name}`;
}
const salutation = customSalutation('Hafid');
console.log(salutation);
// Hey Hafid

So no matter how this method is called or consumed you can always expect to get the same output if you give it the same input. Here is a different case when we have an array called names and right below it a variable nameSalutaions which is the assigned return values from mapping with first the first functioncustomeSalutations as a callback function that will be called on each element of the names array.

const customSalutation = (name) => {
return `Hey ${name}`;
}
const names = ['Hafid', John', 'Lucy''];
const nameSalutation = name.map(customSalutation);
console.log(nameSalutation);
// [
// 'Hey Hafid'
// 'Hey John',
// 'Hey Lucy'
// ]

The output is a salutation for each person. Pure Functions allow you to have the expectation that given the same input you should have the same output, this makes your code a lot more readable since it’s easy to see the mapping between your inputs and your outputs. This is also great for memorization or caching since you can predict the output if you have the same input so instead of calling your Pure Function every single time you have the same input you can save your output in some location and then grab that output whenever you need it. By taking advantage of this you can really optimize your applications.

All right so now that we understand the idea of the same input, the same output let’s take a closer look at what Side Effects are. This term in JavaScript refers to the concept of a function that can alter the external state of your application, this means that a function can alter parts or values of your application that don’t directly reside inside that same method.

There are two common cases where a function can produce a Side Effect.

the first is where a function can go to its outer scope and directly alter the values of those outer variables.

Let’s an example of this scenario:

const show = {
title: 'One peace',
episodes: 120,
}
const watchNextEpisode = () => {
show.episodes = show.episodes +1;
return show.episodes;
}
console.log(watchNextEpisode);
// 121
console.log(watchNextEpisode);
// 122

The method above produces a Side Effect since it changes each time the number of episodes in the show object.

This case is where the method directly mutates its arguments

const comedies = ['The Office', 'House', 'Comunity'];const appendShow = (shows, newShow) => {
shows.push(newShow);
return shows;
}
const shows = appendShow(comedies, '30 Rock');console.log(shows);
// ['The Office', 'House', 'Comunity', '30 Rock'];
console.log(comedies);
// ['The Office', 'House', 'Comunity', '30 Rock'];

The Side Effect here happens when pushing the newShow string to theshows array argument, which is a reference for the comedies array.

The issue happens when it is not clear for some that the original argument passed to the method is going to be altered.

to avoid this scenario let’s take a lot at this code block:

const comedies = ['The Office', 'House', 'Comunity'];const appendShow = (shows, newShow) => {
return [...shows, newShow];
}
const shows = appendShow(comedies, '30 Rock');console.log(shows);
// ['The Office', 'House', 'Comunity', '30 Rock'];
console.log(comedies);
// ['The Office', 'House', 'Comunity']; =]

Now, instead of passing directly to the argument shows, and append the string newShow and then return the new array.

Pure Functions and Side Effects might be really obvious, in some cases, to be identified very well and sometimes they are not. So just like with everything else in your journey of learning JavaScript, it’s gonna take some time for you to train yourself to identify what a Pure Function looks like or what a Side Effect looks like but I hope this article was a great starting point.

About me

An Automation Engineer, a Web Developer, a Data Science enthusiastic, and a Blogger sometimes. Always looking for new challenges so follow me on LinkedIn and never hesitate to contact me for any subject.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store