Search code examples
javascriptnode.jstypescriptweb-worker

Do javascript functions have referential transparency with mutable state?


Reading through this article on Javascript Functional Programming and it mentions Referential Transparency being defined as:

Referential transparency: The function always gives the same return value for the same arguments. This means that the function cannot depend on any mutable state.

IIUC Javascript functions satisfy this requirement even if they depend on mutable state, because two functions cannot operate on shared state even if they are running at the same time?


Solution

  • So to summarize our discussion, yes Javascript functions do have referential transparency as long as the mutable state they depend on does not change.

    In other words the same output will be provided for the same input while the mutable state that the function depends on is held constant.

    This seems somewhat obvious, but for Javascript and functional programming its an important concept / realization because Javascript cannot run the function in two threads at the same time. If we could change the state that the function depends on while the function is running we could create race conditions that are hard to reason about and that would make the function results unpredictable, which is what we are trying to avoid with referential transparency.

    For example a function fn(5), that depends on mutable state x will always return the same result for the same input, as long as x does not change.

    In non Javascript environments it's possible to change x while the function is running, so two invocations of fn(5) could return different results.

    With Javascript if fn(5) returns a different result, we know exactly why. It's because x was changed between invocations of fn(5).