DEV Community

Discussion on: Principles of Functional Programming

Collapse
 
jamesrweb profile image
James Robb

What about if I perform an internal copy of the "items" parameter, like "items1", and then do exactly the same process your function does but over the "items1" container and finally I return "items1". Should now this be a pure function?

As I stated in the article:

Any function that changes its inputs or the value of some external variable is an impure function.

So long as our inputs are unaffected and the output is consistent, the function is pure but if you alter variables you then break the rules of immutability but that's a different point.

If the answer is "no", which would be the reason?

If acting on an internal variable that is thrown away after execution, that is fine so long as the internal variable does not break the rules of pureness itself, for example mutating another internal variable such as:

function add(a, b) {
    let sum = a;
    sum += b;
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

But it does break the rules of immutability which is why it should be avoided to do something like this. We never want to mutate variables but to create immutable deep copies or new values:

function add(a, b) {
    const start = a;
    const withB = start + b;
    return sum;
}
Enter fullscreen mode Exit fullscreen mode

This is a silly example since returning a + b would suffice but if you do need variables then immutable constants are the way to go.

Another point here might be "because we have a loop inside it, which is prone to side effects", correct? But, if this is the case, we have another reason different from: "any function that changes its inputs or the value of some external variable is an impure function."

Loops aren't inherintly bad constructs, they have uses but generally speaking whatever a loop can do, so can mappers, reducers, recursion and so on. For example in the article on the pure functions section I gave the example of calculating the squares of numbers, a pure way to do that without loops would be like so:

function getSquare(x: number): number {
   return x * x;
}

function getSquares(items: number[]): number[] {
  return items.map(getSquare);
}
Enter fullscreen mode Exit fullscreen mode

No loops required.

This definition is clearly different than yours.

Could you please clarify and explain this topic better?

As I stated in the pure functions section:

A pure function is a function which:

  1. Given the same inputs, always returns the same output
  2. Has no side-effects

The first point is the same as the definition the "well-known Developer, Teacher and Writer" stated.

If you need something else clarified though, feel free to ask!