Mateusz Wit
Mateusz Wit

Reputation: 485

Use of external data/operation in JavaScript pure functions

From my understanding, it is completely okay to use an external function (not a callback) inside some other function:

function a() {};

function b() {
    a();
};

And b still can be called a pure function, can it not?

The same goes for some global methods, like:

function c() {
    return Math.sqrt(4);
}

C is still considered pure, because, although Math.sqrt is out of c's scope, Math.sqrt is a pure method.

That is all fine and good, but when I use an external variable like this:

window.isPlaying = false;

function d() {
    return window.isPlaying;
}

Then it becomes impure, right?

And... using an impure function inside a new function makes this new function impure too, doesn't it?

function e() {
    return new Date().getTime();
 }

Is my reasoning okay?

Upvotes: 1

Views: 154

Answers (1)

deceze
deceze

Reputation: 522016

The definition of a pure function states that it must return the same output for the same input, and must itself not cause any observable side effects. If the function is influenced by non-local variables, or returns different outputs despite identical inputs (as is the case with date-based calculations), then it is impure.

It does not matter whether the function calls other functions. The entire point of functional programming and the composition of functions into programs, so calling other functions is part of the routine.

Your analysis is correct: as long as a function is pure and functions it calls to are also pure, it's pure. A single impure function though will make the entire chain of its callers impure.

Upvotes: 3

Related Questions