AlgoDaily

Pure Functions in JavaScript

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Pure functions in JavaScript

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:

function pureReturn(investment) {
  return investment * 1.07;
}

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

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:

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

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?

```java
// Pure function in Java
public static double pureReturn(double investment) {
    return investment * 1.07;
}

// Impure function in Java
public static double roi = 0.07;
public static double impureReturn(double investment) {
    return investment * (1 + roi);
}
```
```javascript
// Pure function in JavaScript
function pureReturn(investment) {
  return investment * 1.07;
}

// Impure function in JavaScript
var roi = 0.07;
function impureReturn(investment) {
  return investment * (1 + roi);
}
```
```python
# Pure function in Python
def pure_return(investment):
    return investment * 1.07

# Impure function in Python
roi = 0.07
def impure_return(investment):
    return investment * (1 + roi)
```
```cpp
// Pure function in C++
double pureReturn(double investment) {
    return investment * 1.07;
}

// Impure function in C++
double roi = 0.07;
double impureReturn(double investment) {
    return investment * (1 + roi);
}
```
```csharp
// Pure function in C#
public static double PureReturn(double investment)
{
    return investment * 1.07;
}

// Impure function in C#
public static double roi = 0.07;
public static double ImpureReturn(double investment)
{
    return investment * (1 + roi);
}
```
```go
// Pure function in Go
func pureReturn(investment float64) float64 {
    return investment * 1.07
}

// Impure function in Go
var roi float64 = 0.07
func impureReturn(investment float64) float64 {
    return investment * (1 + roi)
}
```

Introduction

Question 1

Classify the given code snippets into pure and impure functions:

Code snippet 1:

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

New Screen

Code snippet 2:

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

Higher level

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.

Question-2

Question 2

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

Question 2-2

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

Further-info

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.

Question2

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

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

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

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

Function maxplusone is _____ function (Pure/Impure)

One Pager Cheat Sheet

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.
Open interactive view →