Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 917 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Intro to Recursion - Refactoring to a Pure Function

3:37 JavaScript lesson by

Our previous solution used forEach and a globally available array that could be mutated from inside our function. We can improve upon this and create a function that is easier to maintain & test by swapping our forEach loop for reduce. By removing the global array and instead making getTasks return a value directly we end up with a pure function.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Our previous solution used forEach and a globally available array that could be mutated from inside our function. We can improve upon this and create a function that is easier to maintain & test by swapping our forEach loop for reduce. By removing the global array and instead making getTasks return a value directly we end up with a pure function.

Avatar
William Carroll

I enjoyed the video as the author made the concept of pure functions clearer to me. Correct me if I am wrong, but isn't the refactored function at the end of this video still "impure"? The author claims that it does not rely on any external state; however, within the if-statement, there is a reference to the config variable that exists outside of the function. It seems to me that this function would be more pure if instead the config state was passed into the function. Again, I enjoyed the video. And I may well be wrong about this. Happy to discuss!

In reply to egghead.io
Avatar
Shane

Thanks William. The focus of the lesson was to remove any mutation from within the function, but you are correct - it's not 100% pure for the reason you mentioned. I will update this video with an additional explanation regarding that point. :)

In reply to William Carroll
Avatar
Joel

This lesson video was updated!

Avatar
Bartłomiej

In Array.prototype.reduce method, first parameter is accumulator and second one is currentValue, not previous and next.


Featured course:

Create an SVG Icon System

Create an SVG Icon System

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?