[JavaScript] Pure Function for Clean Code

[JavaScript] Pure Function for Clean Code

Introduction

in this article, I will be talking about pure vs impure function, and why it is a good practice to always try to use pure function if we can. A pure function does not only exist in JavaScript. You can adopt this in almost every programming language if they provide a function.


What Is Pure Function?

A pure function has TWO(2) rules.

  1. Always returns the same result if the same arguments are passed.

  2. Does not cause any side effects

A function that does not fit in any of these rules is called an impure function.

For example:

// pure function
const add = (x, y) => {
    return x += y
}
add(3, 5); // 8 - always

// impure function
const x = 3;
const y = 5;
const add2 = () => {
    return x += y; // 8, 11, 14, 17, and so on
}
add2(); // result changes

Let's have a look at the impure function. Why is it impure -> the second rule (no side effect) was not satisfied. The value of x will increase by 3 as you call the function.

Now, think about which one would be easier to debug, read, understand, and predict the result. It's obviosuly the first one, and that's why we want to use pure function if we can. Pure functions are straightforward. Furthermore, pure functions can minimize the impact that a certain function can give on other functions.

Did you find this article valuable?

Support Lim Woojae by becoming a sponsor. Any amount is appreciated!