Pure Functions

Let's learn and practice pure functions in this lesson.

We'll cover the following

A pure function is a function that has the following characteristics:

  • Its outputs depend solely on its inputs
  • It has no side effect

A side effect is a change in program state or an interaction with the outside world. A database access or a console.log() statement are examples of side effects.

Given the same data, a pure function will always produce the same result. By design, a pure function is independent from the program state and must not access it. Such a function must accept parameters in order to do something useful. The only way for a function without parameters to be pure is to return a constant value.

Use of pure function

Pure functions are easier to understand, combine together, and debug: contrary to their impure counterparts, there’s no need to look outside the function body to reason about it. Still, a number of side effects are necessary for any program, like showing output to the user or updating a database. In functional programming, the name of the game is to create those side effects only in some dedicated and clearly identified parts of the program. The rest of the code should be written as pure functions. Let’s refactor our example code to introduce pure functions.

Get hands-on with 1400+ tech skills courses.