How to use external state in Pure functions?
Hi , Again We have read about the pure functions and impure functions in this article.
We talked about that pure functions doesn’t contain any external state and pure functions also doesn’t give any side effects .
Think about like there is a given scenario you have to take external state in your function but if you are modifying in the function , this will not mutate the external state . It’s not an impossible task . We can try to implement this .
const num= 2;
function updateNum(newNumber, number){
let number_1= number;
number_1= newNumber;
newNumber= newNumber+4;
return newNumber;
}updateNum(num)
Take a look of this code , we are passing external state of num to a function updateNum . This updateNum function will return a newNumber = 2+ 4, 6.And num value will not be changed .
How it is possible ?-
First we have taken num as external state , we are passing num to the function but the number has been cloned to number_1 and number_1 is returned as newNumber . we have did the add operation to newNumber . So nowhere I am using the external state only using to clone in new state .
Can I say “it is pure function” ?
Absolutely Yes , we have not changed the external variable . Okay we have also the solved the problem, we can determine the behaviour of function . If we are passing the num into updateNum , it will always return the same output as num+4.
Array Cloning (ES6)
Why not we will take a chance to clone an array?
const nums= [1,2]
const numbers= nums// Now I will try to append the numbers numbers.push(3)//Now
nums= [1,2,3]
numbers= [1,2,3]
In this code nums is changing , if we are changing numbers but why ? Because numbers has taken only the reference (memory ) of nums .So if we are adding any value to that reference , it will be changed in all references of same variable.
So here is a way to copy the values , not the reference . We can use spread operators to copy the array values.
const nums= [1,2]
const numbers= [...nums]numbers.push(3)// Now nums and numbers
nums = [1,2]
numbers= [1,2,3]
There is another way to copy the array values .
const nums= [1,2]
const numbers = Array.from(nums)
This is from my side about the topic . If you have any doubt , please comment on this.