What's Pure Function in JavaScript?

What's Pure Function in JavaScript?

Wed Jun 23 2021

11 min read

JavaScript

Hello World,

One of the most known questions, especially in interviews, is about pure functions and what they are… so we will talk about pure functions in this article.

what are pure functions?

It’s the atomic building block of functional programming. they are very simple and easy to test.

The function can be called a pure function if these conditions are applied:

Let’s focus on each of them:

The same inputs always return the same outputs

This means that we always get the same output whenever we use the function and pass the same input.

for example, we have this function.

function sum(x, y) {
  return x + y
}

sum(2, 3) // will return always 5

whenever we pass the same input 2, 3, we get the same output 5.

But in the following example.

let num = 5
function sum(x) {
  return (num += x)
}

sum(2) // will return 7
sum(2) // will return 9

we have a shared state here, which is a bad practice (we don’t use it unless we need to do things that way) because we can’t predict the return value of the function now, and became not a pure function.

So in summary, a pure function is a function that returns the same output always whenever we call it and pass the same input.

No side effects

the side effects of a function are one of the following:

In general, the function implementation should be only about calculating the final output and nothing else.

Note: we should not always use pure function and it’s not the best solution as may you think, because we might need to call HTTP requests, change the file system, or query the DOM tree.

That’s it for today’s article, if you have any suggestions, then don’t hesitate to contact me anytime.

JavaScript