Pure versus impure functions

0
287
views

Understanding pure and impure functions is a simple transition into cleaner, more role-based and testable code. In this post we’ll explore pure and impure functions by looking at a simple Body Mass Index (BMI) calculator that estimates your “healthy weight” by some simple input factors of height and weight. BMI isn’t considered the most reliable tool for checking your weight, but that’s not the point of this article 🙂

Impure functions

An impure function is a function that mutates variables/state/data outside of its lexical scope, thus deeming it “impure” for this reason. There are many ways to write JavaScript, and thinking in terms of impure/pure functions we can write code that is much easier to reason with.

A pure function is much easier to comprehend, especially as our codebase may scale, as well as role-based functions that do one job and do it well. Pure functions don’t modify external variables/state/data outside of the scope and return the same output given the same input. Therefore it is deemed “pure”.

Read Full Article

LEAVE A REPLY

Please enter your comment!
Please enter your name here