Pure vs Impure Functions
23 June, 2022
22
22
0
Contributors
These are the two terms that you always hear in a programming language called Pure and Impure functions.
You know Pure Function
is always dependent on arguments and there should not be any side effects.
What hack is Side Effects? β οΈ
When you try to use external code in the function or if you are mutating a variable then it creates a Side Effect.
Example:
As you can see in the above snippet, mul
the function has a dependency on an outer variable called num
. Also, mutating num
value, which makes its impure function.
Letβs checkout one more quick example:
So, what do you think about the above snippet? π€
.
.
.
Yeah! this is also an impure function π΅βπ«
As you all know that JavaScript is synchronous, using console
or any callback
or promise/fetch
will make the function asynchronous.
Here using the console
, which is a Web API makes it an impure function.
Let's checkout other side effects with examples:
-
DOM Manipulation, any callback or reading/writing files
-
Updating or Modifying a global variable in pure function
-
Here also, mutating outer variable which is depending on an external variable.
Let's Understand the Pure and Impure function, as now you have an idea of the side effects
Pure Function
- It always returns theΒ same resultΒ if the same arguments are passed
- It never depends on any state/data/change during the execution of a program
- It always returns something
- Here, writing test cases will be straightforward
Impure Function
- Changing the internal state of any argument which has been passed
- It may take effect without returning anything
- Writing test cases will be a bit complicated as there may be side effects
Pure and Impure Methods
These are pure methods:
- Array.map()
- Array.reduce()
- Array.filter()
- Array.concat()
- ... (spread syntax, which is mostly used to create copies)
These are impure methods:
- Array.splice()
- Array.sort()
- Date.now()
- Math.random()
Bonus Point π
You can clone an external state into a pure function.
Cloning an external state into a pure function does not make the function impure.
Example:
In the above snippet, you are using the ...
spread operator in the fullName
function. It will create a clone of it and then update it. So, it doesn't depend on the name
variable.
Thanks for reading the article!
Hope you found this article useful. If you have any questions, feel free to drop them into the comment section.