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

Try this exercise. Click the correct answer from the options.

Question 1

Classify the given code snippets into pure and impure functions:

Code snippet 1:

SNIPPET
1function average(a, b) {
2  var average = a + b / 2;
3  return average;
4}

Click the option that best answers the question.

  • Pure
  • Impure

Let's test your knowledge. Click the correct answer from the options.

Code snippet 2:

JAVASCRIPT
1var a = 5;
2var b = 7;
3function average(a, b) {
4  return a + b / 2;
5}

Click the option that best answers the question.

  • Pure
  • Impure

Elevating the Understanding of Pure and Impure Functions

1-to-1 Correspondence: The Hallmark of Pure Functions

When we talk about a 1-to-1 correspondence in pure functions, envision a well-organized filing cabinet. Each input is like a label on a file folder, and each output is the content inside that folder. You pull out a folder with a specific label, you'll find exactly the same content every single time. It's predictable and independent, unaffected by any chaos that may be happening in the office around it.

Key Takeaways:
  • Predictability: Always know what you're getting.
  • Isolation: External changes in the code environment do not alter the function's behavior.
  • Testability: Because they're so predictable, pure functions are easier to test. It's like an open-book exam where you already know all the answers.

1-to-Many Correspondence: The Complexity of Impure Functions

Now, let's think of impure functions as a magical filing cabinet. These are still folders and labels, but the content inside might change based on the 'mood' of the office—say, the weather outside, or the time of day. Pull out a folder in the morning, and it might contain something entirely different by the afternoon. This is because the function is sensitive to external factors—like global variables or states—that could affect its output.

Key Takeaways:
  • Flexibility: Can adapt to different needs or conditions.
  • Complexity: Harder to predict and could lead to unexpected outcomes.
  • Maintenance Challenge: Because of their unpredictability, impure functions are harder to debug and maintain. It's a mystery novel where the ending can suddenly change.

Making an Informed Choice

Choosing between pure and impure functions depends on the task at hand:

  • Pure Functions: Go for these when you need predictability and easier maintenance.
  • Impure Functions: Choose these when you need flexibility and the ability to adapt to changing conditions.

Let's test your knowledge. Is this statement true or false?

Question 2

Any pure function can be used to express one to many functions (True/False)

Press true if you believe the statement is correct, or false otherwise.

Let's test your knowledge. Is this statement true or false?

The output of pure functions depend on global variables (True/False)

Press true if you believe the statement is correct, or false otherwise.

Understanding Purity in Nested Function Systems

Nested functions—a function within a function—are a common sight in modern programming. The question arises: when is such a nested system considered "pure"?

Criteria for Purity in Nested Functions

A nested function system is pure if, and only if, calling the inner function does not produce any side effects. In simpler terms, invoking the inner function should not alter any state or produce different outcomes beyond its own scope.

Common Side Effects

Side effects are any operations that extend beyond the local environment of the function itself. Here are some common and not-so-common side effects to watch out for:

  • HTTP Requests: Making a call to an external API or database.
  • Global Variable Manipulation: Changing the state of variables not confined within the function.
  • Output Operations: Writing to a screen, console, or file.
  • DOM Alterations: Any changes to the structure or content of a webpage.
  • Random Number Generation: Functions like Math.random() which produce non-deterministic results.
  • Time-based Operations: Anything dependent on the current time or date.
  • State Changes in Storage: Altering cookies, local storage, or other client-side storage mechanisms.
  • Event Triggering: Emitting or broadcasting events to other parts of the application.

By avoiding these side effects in your nested functions, you ensure that they maintain their purity. This makes the code easier to understand, reason about, and test.

Build your intuition. Fill in the missing part by typing it in.

Question 3 The function Math.max() gives the largest of the input paramters. A very simple illustration of the same is given below:

JAVASCRIPT
1console.log(Math.max(1, 2, 3));
2// expected output: 3

With this knowledge, answer the following questions pertinent to the code snippet given below:

JAVASCRIPT
1function maxplusone(a, b) {
2  return Math.max(a, b) + 1;
3}

Function maxplusone is _ function (Pure/Impure)

Write the missing line below.

One Pager Cheat Sheet

  • The code snippet above is a pure function because the output is solely dependent on the input variables and not on any external environment, as it does not contain any variable declared outside of the function.
  • The non-deterministic nature of the impure function in code snippet 2, due to external variables, makes it inherently unpredictable.
  • A pure function has a 1-to-1 correspondence between input and output, while an impure function has a 1-to-many correspondence due to its dependence on outside variables.
  • True, a pure function can be used to create a 1-to-many relationship between input and output.
  • Pure functions are deterministic and reliable as their output is solely determined by the values of the input parameters and does not depend on global variables.
  • A nested function system is considered pure if it does not trigger any side effects such as an HTTP request, mutation of data, printing to a screen, DOM manipulation or Math.random().
  • The function maxplusone is a pure function with no side effects, as it only calls Math.max() and adds one to its result.