Dart 101: A Pure Function

nabilmahmuddev

Nabil

Posted on October 14, 2024

Dart 101: A Pure Function

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);
}
Enter fullscreen mode Exit fullscreen mode

This is yet another example of a function having a side effect:

int villagePopulation = 50000;
String shoutOutLoud(String message) {
  villagePopulation = 1;
  return message;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
nabilmahmuddev
Nabil

Posted on October 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related