Pure Functions in JavaScript. Why should we know about them as early as possible?

Pure Functions in JavaScript. Why should we know about them as early as possible?

Daily short news for you
  • Revealing how readers of 2coffee.dev will read articles in the future 🫣

    » Read more
  • Microsoft has decided to "transform" the Windows Subsystem for Linux (WSL) on Windows into an open-source project 👏

    Back when I was still into gaming on the computer, I absolutely hated Ubuntu. Probably because it couldn't run games. But programming with Linux kernels was such a delight. So I found myself in a dilemma. I wanted to use Linux but had to stick with Windows.

    Microsoft's release of WSL was like a necessary savior. Quite cool. It's simply using Linux commands on Windows. However, it's still not entirely "smooth" like a real operating system. Now that they’ve open-sourced it, I hope there will be even more improvements 🙏

    microsoft/WSL

    » Read more
  • When researching a particular issue, how do people usually take notes? Like documents found, images, links, notes...

    I often research a specific topic. For example, if I come across an interesting image, I save it to my computer; documents are similar, and links are saved in my browser's Bookmarks... But when I try to find them later, I have no idea where everything I saved is, or how to search for it. Sometimes I even forget everything I've done before, and when I look back, it feels like it's all brand new 😃.

    So I'm nurturing a plan to build a storage space for everything I learn, not just for myself but also with the hope of sharing it with others. This would be a place to contain research topics, each consisting of many interconnected notes that create a complete notebook. Easy to follow, easy to write, and easy to look up...

    I write a blog, and the challenge of writing lies in the writing style and the content I want to convey. Poor writing can hinder the reader, and convoluted content can strip the soul from the piece. Many writers want to add side information to reinforce understanding, but this inadvertently makes the writing long-winded, rambling, and unfocused on the main content.

    Notebooks are created to address this issue. There's no need for overly polished writing; instead, focus on the research process, expressed through multiple short articles linked to each other. Additionally, related documents can also be saved.

    That’s the plan; I know many of you have your own note-taking methods. Therefore, I hope to receive insights from everyone. Thank you.

    » Read more

Problem

I'm 26 years old this year, and I've been maintaining a few projects. Sometimes I come across cases where some of my teammates do things like this:

function convertBirthdayToAges(person) {
  const year = new Date().getFullYear(); // 2021
  return person.map(p => p.age = year - p.year);
}
...  
const persons = [{name: 'Nguyễn Văn A', year: 2000}];
convertBirthdayToAges(persons);
console.log(persons); // [{name: 'Nguyễn Văn A', year: 2000, age: 21}]

At first glance, the above function seems normal, but if you notice, after persons goes through the convertBirthdayToAges function, it is attached with an additional attribute age.

Or another example like this:

let year = 2020;
function afterManyYear(num) {
  return year + num;
}
afterManyYear(5) // 2025;

....  

year = 2025;
afterManyYear(5) // 2030;

In the example above, initially when calling afterManyYear(5), the result is 2025, but later, when year is changed to 2025, afterManyYear(5) now returns 2030.

This may seem normal, but imagine in a maintenance phase where you don't know where year was changed, it can be a disaster. You may argue why not declare year with const: const year = 2020;? Well, I think when they chose to declare with let, they already had it in mind that year could be changed at any time.

If you are someone who regularly does these things and see the inconvenience they bring, then it's time for you to know about the concept of Pure Functions.

What is a Pure Function?

Pure function is exactly what its name suggests: "Pure function".

It is a JS function that satisfies two conditions:

  • The same inputs always return the same outputs.
  • No side-effects.

The same inputs always return the same outputs

Pretty straightforward. For example:

function add(x, y) {
  return x + y;
}
add(1, 2); // 3
add(1, 2); // 3

For each pair of x,y passed in, the return value never changes.

This function won't satisfy:

let x = 1;
function add(y) {
  return x + y;
}
add(1); // 2
x = 2;
add(1); // 3

When a function guarantees this condition, understanding and debugging become much easier.

No side-effects

Side-effects are the "effects" that come along with a function, such as:

  • Changing the value of an input.
  • console.log
  • HTTP calls (fetch/AJAX).
  • Changing a file (fs).
  • Querying the DOM.
  • ...

In general, besides the things listed above, side-effects also include any tasks within a function that are unrelated to the final computation result.

In the example in the opening part, we saw that convertBirthdayToAges modified the value of the input persons. If by any chance, persons loses one of its attributes, then it becomes a hassle.

To solve this issue, instead of directly modifying persons, let's return a new object:

function convertBirthdayToAges(person) {
  const year = new Date().getFullYear();
  return [...person.map(p => p.age = year - p.year)];
}

const persons = [{name: 'Nguyễn Văn A', year: 2000}];
const newPersons = convertBirthdayToAges(persons);
console.log(persons); // [{name: 'Nguyễn Văn A', year: 2000}];

In the above example, I used the spread syntax (...) to create a new array object. Note that it can only create a "shallow" copy of an object. To create a "deep" copy, I recommend using the clone package available on npm.

An application cannot be without side effects

That's right, your application cannot function without including the "effects" listed above, except for extremely simple ones. They cannot function without reading/writing to a database or selecting an element in the DOM. But the important thing is to minimize as much as possible or structure independent side-effect code segments.

For example, an update data function:

// In this example, Person is a sequelize model

// This update function is the only one that directly has side-effects
function update(payload) {
  return Person.update(payload);
}

function updatePerson(body) {
  const name = body.name.trim();
  const year = +body.year;
  return update({ name, year });
}

Summary

Pure functions are not a new concept, but the benefits they bring during the development and maintenance of a product are extremely valuable based on my working experience.

Through the examples above, I hope you realize the benefits of applying pure functions to current and future projects. A slight change in expression can bring many benefits in maintaining code later on.

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (1)

Leave a comment...
Avatar
Trịnh Cường4 years ago

Bài viết rất hay và bổ ích. cảm ơn bạn rất nhiều vì đã chia sẻ. hóng những bài viết mới của bạn. Chúc blog ngày càng lớn mạnh. tặng bạn 1 share

Reply
Avatar
Xuân Hoài Tống4 years ago

Nhớ ghé blog của mình để đọc những bài mới hơn nhé bạn.