Pure functions in EcmaScript

Claus Reinke claus.reinke at talk21.com
Wed Nov 28 09:19:19 PST 2012


>> With many new functional programming possibilities (like map, reduce, 
>> filter, lambdas) there are many scenarios where the implementer should 
>> use pure (or as I renamed it in another reply, side-effect-free) 
>> functions.
> Why "should"? What is the problem if people don't?

In the non-sequential versions, side-effect-free operators
give more flexibility in scheduling, eg, splitting an array
into sub-arrays, running partial loops on separate processors,
then combine the results.

In sequential code, side-effect-free operators give more
flexibility in refactoring and simplify program understanding
(code segments without access to global state have smaller APIs).

As pointed out by Andreas, achieving that is not easy in JS.
Even when some kind of soft or gradual type system finally
takes over the JS world,-) it'll still have to deal with a lot of
needlessly side-effect-based APIs. So my preference would be
to make sure that ES.next has side-effect-free, expression-level
APIs next to the existing side-effect-based, statement-level APIs, 
wherever possible (starting with object updating/extension).

The definition used by Marius seems to call for closed functions
(no non-local variables), which is not directly related. It sounds
as if he wants to allow local side-effects, as long as they do not
propagate outside the local call stack, but that is not as simple
as using closed functions. Andreas provided counter-examples.

Claus
 


More information about the es-discuss mailing list