Refactoring Functions
Pure Functions Vs Impure Functions
Hello, in this post I'll explain the difference between pure and impure functions in JavaScript, and How to convert from impure to pure function.
Let's Begin with examples.
Impure Function
In the first code snippet if you call the function forEachFunc
another time, you'll end up with different result and so on for each call. The impure function not depend on its arguments only but it may change from outside the function itself and this called "Side Effect".
Side Effect
The side effect doesn't limited to mutations it may include network(HTTP calls, DB calls, user inputs, ...etc). You can know more about side effects in impure functions related to JavaScripts in the resources in the last article.
Pure Function
In the second code snippet, whenever you called the function you'll get the same result, because it only depends on its arguments.
Pure or Impure?
It depends, but if the two options are available to3 your situation, you have to use the pure functions, In pure functions you don't have to search for another variables that may change your functional result (Avoiding the side effects), easily to trace, more clearer, more readable.
forEach Vs Map, Which one is better?
OK, It depends. if you want to mutate an exist list for example, forEach
will be better, but this will consider as a side effect according to its explanation from MDN forEach:
forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
map()
might be better if you want to mutate data or create a new array from another array. it's faster, side effects avoider, more readable.
In the following example it's better to use map()
over forEach()
And this if we wrote it using map()
Closing
In the end I'm not expert in JavaScript or functional programming, but I felt that I have things to say about this. So I put down some resources to read more. follow me on twitter.
Originally published on my blog
Thanks for reading, and I hope this was hopeful to you!
Read Further...
- Understanding Javascript Mutation and Pure Functions
- Identify Side Effects by Comparing Pure and Impure JavaScript Functions
- Master the JavaScript Interview: What is Functional Programming?
- Pure versus impure functions
- mostly-adequate-guide Book, Chapter 3: Pure Happiness with Pure Functions
- JavaScript: What Are Pure Functions And Why Use Them?
- Javascript and Functional Programming — Pt. 3: Pure Functions
- Map.prototype.forEach()
- JavaScript — Map vs. ForEach
Top comments (0)