Functional Programming and Pure Array Updates

Learn about the functional programming and the pure array updates.

Functional programming

Functional programming is a style of programming that has become very popular in recent years, partly due to purely functional languages, such as Clojure, Scala, and Erlang. JavaScript has always supported functional-style programming, because functions are first-class objects. The techniques we’ve covered so far—such as using anonymous functions as arguments, returning values to other functions, and creating closures—are all fundamental elements of functional programming.

Pure functions

A key aspect of functional programming is its use of pure functions. A pure function is one that adheres to the following rules:

  • The return value of a pure function should only depend on the values provided as arguments; it doesn’t rely on values from somewhere else in the program.
  • There are no side effects: a pure function doesn’t change any values or data elsewhere in the program. It only makes non-destructive data transformations and returns new values, rather than altering any of the underlying data.
  • A pure function has referential transparency. Given the same arguments, it will always return the same result.

In order to follow these rules, any pure function must have:

  • At least one argument: Otherwise, the return value must depend on something other than the arguments of the function, breaking the first rule.
  • A return value: Otherwise, there’s no point in the function (unless it has changed something else in the program, in which case, it has broken the “no side effects” rule).

Pure functions help to make functional programming code more concise and predictable than in other programming styles. Referential transparency makes pure functions easy to test, as they can be relied on to return the same values when the same arguments are provided. Another benefit is that any return values can be saved in memory because they’re always the same, making the function more efficient. The absence of any side effects tends to reduce the amount of bugs that can creep into our code, because there are no surprise dependencies. Pure functions only rely on any values provided as arguments.

Let’s take a look at how not to write a pure function. The next example shows an impure function that returns the value of adding two values together:

Get hands-on with 1200+ tech skills courses.