[JavaScript] Pure Function for Clean Code
Table of contents
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.
Always returns the same result if the same arguments are passed.
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.
Subscribe to my newsletter
Read articles from Lim Woojae directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Lim Woojae
Lim Woojae
Computer Science Enthusiast with a Drive for Excellence | Web Development | Passionate About Tech & Innovation