My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Pure Function in JavaScript

Pure Function in JavaScript

Taha Mahmoud's photo
Taha Mahmoud
·Feb 11, 2022·

3 min read

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.

// example

const sum = (x, y) => x + y; // pure function

sum 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.



// example

const userName = 'Alex';
const addedName = (param) => '${userName} is a web ${param}'

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


// example

const fetchLoginToken = externalAPI.getUserToken

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.

  • some side effects can be like.

    • making on HTTP call
    • mutation(changing)
    • 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 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.


  • Pure Function Features.

    1- we can always predict the output.

    2- function programming reduces the number 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.