Pure Functions in Detail
Strengthen your concepts about pure functions, non-pure functions, and props through interactive examples.
We'll cover the following...
As pure functions form a fundamental principle of React, let’s explain them a little more with the help of some examples. Much of this will sound more theoretical and complex than it is in practice. However, a strong understanding of pure functions is essential for modern React developers.
Examples for a pure function
Our first function is passed a number, doubles it, and returns the result. It does not matter whether the function is being called 1, 10, or 250 times. For example, if we pass the number 5
as a value, we will receive a 10
every time. The same input always leads to the same output.
function pureDouble(number) {return number * 2;}for(var i = 1 ; i <= 10; i+=1) {console.log(pureDouble(5));}
Our second function takes in a number and the browser’s window size as arguments and returns their summation. This is a pure function because we are passing the window width as another argument. Although the function is dependent on window width, by calling pureCalculation(10, window.outerWidth)
the result will be pure as if the same input is passed. The same output is generated each time.
function pureCalculation(number, outerWidth) {return number + outerWidth;}for(var i = 1 ; i <= 10; i+=1) {console.log(pureCalculation(10, 1920));}
The above example will become easier to understand once the function is reduced to its fundamental ...