DEV Community

Cover image for Pure Function in JS
T Mahmoud
T Mahmoud

Posted on

Pure Function in JS

a pure function is one of the concepts of functional programming in javaScript.

  • pure function: don't use the global variable scope in order to achieve principle pure function because the function is only dependent on its own input.

this gives us the pure function if I give it the same input will return always the same output every time will be executed.

Image description

add is a pure function because the output is dependent on only its own arguments that can be received from the function, therefore, if the function takes the same input will return always the same output.

Image description

in this example, create function is not pure because dependent on another variable from out the scope it owns.

Image description

and from the other cases, the function can be impure function is in the cases API function because in some cases the function sometimes will work, sometimes the server will be down, we will get an error 500 or 404, and in the future, the API may change, therefore, we can say that fetchLoginToken isn't pure function.

  • pure function won't cause any side effects. A side effect is any change in the system.

1- some side effects can be like.
2- making on HTTP call
3- mutation(changing)
4- obtaining user input

  • there are some reasons for writing pure function.

1- readability: side effects make code hard to read, then if the function is pure is easy to read it and understand it in an easier way.

2- testability: because the pure function is deterministic by
nature, therefore, writing the unit testing is very easy.

3- reusability: thinking in a pure function as a little bit of part logic because dependent on only its own input, then we can easy to use in different parts of our project.

  • Features of the pure function.

1- we can always predict the output.
2- function programming reduces the numbers of lines of code.
3- test is easy because does not change the state of the variable.

last but not least, in the JavaScript data types like string, Boolean, and number they are immutable opposite the data structure is like array and object they are mutable because they collect a set of data, and apparently because they are non-primitive data type, and therefore if there is any change in the state of the old array, it is considered an impure function.

if you would like to read more about the pure function you can check this link you can find some links explaining that in an easier way.

Top comments (0)