Pure functions in EcmaScript

Andreas Rossberg rossberg at google.com
Wed Nov 28 04:20:46 PST 2012

On 28 November 2012 12:50, Marius Gundersen <gundersen at gmail.com> wrote:
> Has there been any work done on pure functions in EcmaScript? The way I
> imagine it, there would be a way to indicate that a function should be pure
> (by using a symbol or a new keyword, although I understand new keywords
> aren't terribly popular). The pure function is not allowed to access any
> variable outside its own scope. Any access to a variable outside the scope
> of the function would result in a Reference Error, with an indication that
> the reference attempt was made from a pure function. This also applies to
> any function called from within the pure function. The entire stack of a
> pure function must be pure. This also means the pure function cannot access
> the [this] object. Only the parameters  passed to the function can be used
> in the calculation.
> The syntax could be something like this (the @ indicates that it is pure):
> function sum@(a, b){
>   return a+b;
> }
> var sum = function@(a, b){
>   return a+b;
> }

A couple of comments.

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.

Second, due to the extremely impure nature of JavaScript, there aren't
many useful pure functions you could even write. For example, your
'sum' function is not pure, because the implicit conversions required
by + can cause arbitrary side effects.

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


More information about the es-discuss mailing list