DEV Community

Zeyad Etman
Zeyad Etman

Posted on

Refactoring Functions in JavaScript

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

impure1

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

pure1

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.

performance between map() vs forEach()

In the following example it's better to use map() over forEach()

forEach() example

And this if we wrote it using map()

map() example

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...

Top comments (0)