Mark As Completed Discussion

Understanding Pure and Impure Functions in JavaScript

What are Pure Functions?

Pure functions are akin to reliable friends who always give you the same advice when you ask the same question. In other words, they produce the same output for the same input, irrespective of the world around them.

Characteristics:
  • Depend solely on input parameters.
  • Do not affect or rely on external variables or states.
  • Predictable: Same input will always yield the same output.
Example: Pure Function

Here's a simple example. Suppose we want to calculate the return on an investment, assuming a 7% annual appreciation. The code might look like this:

JAVASCRIPT
1function pureReturn(investment) {
2  return investment * 1.07;
3}

In this example, the function pureReturn depends solely on the investment parameter, nothing else.

Pure functions in JavaScript

Why Pure Functions Matter

The key feature here is the function's complete independence from external variables. It's like a self-contained eco-system that doesn't need to import or export anything to function correctly.

What are Impure Functions?

Impure functions are the opposite. They're like unpredictable friends whose advice can change based on external factors. They could produce different outputs for the same input due to external variables or states.

Characteristics:
  • May depend on external variables or states.
  • Could affect external variables.
  • Unpredictable: Same input might yield different outputs based on external conditions.
Example: Impure Function

Here's how to transform our previous investment calculation into an impure function:

JAVASCRIPT
1var roi = 0.07;
2function impureReturn(investment) {
3  return investment * (1 + roi);
4}

Notice how the function now depends on an external variable roi, which can change over time. This introduces unpredictability.

Pure functions offer predictability and are easier to test and debug. Impure functions offer flexibility but can introduce complexity and unpredictability.

As you continue through this tutorial, ponder over these questions:

  • Can you identify if a function is pure or impure just by looking at it?
  • What could be the advantages of using pure functions in a project?
  • How do impure functions affect code maintainability?
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment