li_
li_

Reputation: 124

How is the following a pure function?

It states here that the following is a pure function:

function insert(DB, user) {
    return function() {
        throwIfUserExists(DB, user);
        var savedUser = saveUser(DB, user);
        return savedUser;
    }
}

and that the following is an impure function:

function insert(user) {
    if (DB.exists(user.id)) {
        throw Error("users exists");
    }
    var id = DB.insert(user);
    user.id = id;
    return user;
}

I don't understand how the first function is pure, since it returns a function that produces side effects. Am I wrong and if not, how could the function be written to be pure?

Upvotes: 1

Views: 405

Answers (1)

Shailendra Pal
Shailendra Pal

Reputation: 123

A pure function is a function which:

  • Given the same input, will always return the same output.
  • Produces no side effects.

Now pay attention to the first point. In your first example, as long as you keep sending in the same DB and user the output would be the same. The construction of savedUser or throwIfUserExists functions would affect the output of the first insert fn but the insert function in essence would be a pure function.

However, in the second function the output would be different for each call even though the user is the same. To be precise, the line user.id = id; is the one that is producing the "side effects".

Read Eric Elliot's article on pure functions : https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976

Upvotes: 3

Related Questions