Pure functions in EcmaScript

Andreas Rossberg rossberg at google.com
Wed Nov 28 05:52:49 PST 2012


On 28 November 2012 14:39, Marius Gundersen <gundersen at gmail.com> wrote:
> On Wed, Nov 28, 2012 at 1:20 PM, Andreas Rossberg <rossberg at google.com>
> wrote:
>> First, your definition of "pure" is not quite correct. Any function
>> that even _returns_ locally created state in some form (i.e., a new
>> object), is impure.
>
> Fair enough. A better name would probably be side effect free functions.

Well, observable allocation of state, or assignment to parameters,
_are_ side effects.

On the other hand, accessing non-local bindings that are (deeply)
immutable does not constitute an effect, yet you want to forbid it.

Seriously, what is the use case for this rather strange definition?


>> Last, short of a static type-and-effect system, I don't see how the
>> necessary checks could be implemented without imposing significant
>> overhead on almost every primitive operation -- because every
>> function, and hence almost any piece of code, might potentially end up
>> with a "pure" function in its call chain, and would need to check for
>> that.
>
> I'm not an implementer of EcmaScript, so I don't have deep knowledge of how
> this could be implemented. I would imagine that a subset of a true pure
> function, where the only restriction would be that only variables passed as
> arguments to the function exist in the scope, would be relatively easy to
> implement. Wouldn't this be a faster implementation than todays functions,
> which have to keep track of scope? These side-effect-free functions would
> only need to contain the variables passed as parameters in their scope.
> Accessing anything outside the scope would result in a reference error.

Modern JS implementations don't do the kind of runtime bookkeeping of
scopes that you seem to assume. Compiled code doesn't even know what a
scope is, it just accesses hardcoded indices into the stack or into
some heap arrays.

/Andreas


More information about the es-discuss mailing list