22
loading...
This website collects cookies to deliver better user experience
const add = (a:number, b:number):number => a + b; // PURE FUNCTION
add(2, 3) // 5
const addRand = (a:number) => {
const rand = Math.random();
return rand + a;
} // IMPURE FUNCTION
addRand
is not a pure function because it will not return the same output given the same input. Any function that make calculations based on random numbers are not pure functions. However we see that the first function will always return the same output 5
as long as we pass in 2
and 3
. Pure functions are at the heart of functional programming, they are quite easy to test and debug and they don't affect anything on the global scope, we can stack pure functions on top of each other to create higher order functions.const add = (a:number, b:number):number => a + b; // PURE FUNCTION
const square = (a:number):number => Math.pow(a, 2); // PURE FUNCTION
const addAndSquare = add(square(2), square(3))
console.log(addAndSquare) // 13tt
const makeNumString = num => num2 => num + num2.toString();//
const num = makeNumString(2)
console.log(num(1)) // '3'
Side Effects
, impure functions and side effects are not totally bad and we use a lot of impure functions that cause many side effects in our codes daily. Side effects are results of impure function. A function that changes a variable that is not declared in it's scope is an impure function. While the result of that variable being changed due to the impure function is a side effect. In a more broad sense a side effect can be described as a change in the state of our application caused by an impure function. Let's look at another example of an impure function.const state = { name: 'Job', likes: 'hardship' };
// IMPURE FUNCTION
const impureFunc = (obj) => {
sate.name = 'Dan';
return Obj
}
// ANOTHER IMPURE FUNCTION
const impureFunc2 = (obj) => {
const obj.field = 'value'
return obj
}
// ANOTHER IMPURE FUNCTION
const impureFunc3 = obj => console.log(obj)
// Reverse the array
const reverseArr = arr => arr.reverse() // Reverses an array
const getRandElement = arr => arr[Math.random() * arr.length]; // Picks a random element from an array
const arr = [1, 2, 4, 8, 9, 10, 21];
const randElement = getRandElement(reverseArr(arr))
console.log(randElement) // logs out a random element