Nabil
Posted on October 14, 2024
A very brief intro:
Before getting to know what a pure function is we had better learn about side effects. If a function prints anything to the console or changes any value outside of its own block then it is having side effects. To put it simply, it is having effect outside of its own tiny world i.e. the area defined by two curly braces.
This is one example of a function having a side effect:
void shoutOutLoud(String message) {
print(message);
}
This is yet another example of a function having a side effect:
int villagePopulation = 50000;
String shoutOutLoud(String message) {
villagePopulation = 1;
return message;
}
A pure function:
A function that takes its inputs and only returns its output without affecting any other stuff in a program is called a pure function. In a word a function that do not impose any side effects is a pure function.
Following is an example of a pure function:
String shoutOutLoud(String message) {
return message;
}
The above mentioned function shall only return the message which is of string type. It will not affect anything outside of it or print anything to the screen.
Posted on October 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.