codewithjohn.dev
Published on

Pure Functions in JavaScript

Table of Contents

What are Pure Functions?

JavaScript's pure functions don't change variables outside of their scope; instead, they always return the same result for the same input and have no side effects.

Pure functions are functions that contain the following characteristics:

  • Always returns the same output for the same input: This predictability makes pure functions ideal for unit testing and debugging, as you can be confident that they won't produce surprising results based on external factors.
  • Has no side effects: Pure functions don't modify global variables, access external resources like databases, or perform actions like logging. This isolation keeps their behavior consistent and eliminates the risk of unintended consequences.

Here are some code examples:

  1. Simple Calculation:
function add(x, y) {
  return x + y
}

const result1 = add(5, 3) // result1 will always be 8
const result2 = add(5, 3) // result2 will also be 8

This add function is pure. It takes two numbers as input and returns their sum without modifying any external variables.

  1. String Manipulation

Let's see how to avoid an impure approach and embrace purity:

Impure:

let greeting = 'Hello'

function sayHello() {
  greeting += ', World!' // Modifies the global variable
  console.log(greeting)
}

sayHello() // Output: Hello, World!
sayHello() // Output: Hello, World, World! (Unexpected behavior)

Pure:

function createGreeting(name) {
  return `Hello, ${name}!`
}

const message1 = createGreeting('World')
console.log(message1) // Output: Hello, World!
const message2 = createGreeting('Everyone')
console.log(message2) // Output: Hello, Everyone!

The createGreeting function takes a name and returns a new greeting string, keeping the original data intact.

  1. Array Transformation:

Impure:

const numbers = [1, 2, 3]

function doubleNumbers(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] *= 2 // Modifies the original array
  }
  return arr
}

const doubledNumbers = doubleNumbers(numbers)
console.log(doubledNumbers) // Output: [2, 4, 6]
console.log(numbers) // Output: [2, 4, 6] (Original array also modified)

Pure:

function doubleEach(arr) {
  return arr.map((number) => number * 2)
}

const doubledNumbers = doubleEach(numbers)
console.log(doubledNumbers) // Output: [2, 4, 6]
console.log(numbers) // Output: [1, 2, 3] (Original array remains unchanged)

The doubleEach function uses the map method to create a new array with doubled values, leaving the original numbers array untouched.

Conclusion:

Your JavaScript code will become more predictable, modular, and testable if you use pure functions. You can write programs that are clearer, more logical, and easier to maintain by understanding and successfully following their guiding principles.