4/16 lessons25%

Definition and Characteristics

Pure functions are a foundational concept in functional programming and the key to writing predictable, bug-free code. Let’s break down what pure functions are and why they matter.

Pure Functions

A pure function is a function that:

  1. 1
    Produces the same output for the same input every time (deterministic behavior).
  2. 2
    Does not cause side effects, meaning it doesn’t alter external state or depend on external variables.

Think of pure functions as mathematical functions. For example: The square of a number is always the same, no matter when or how many times you calculate it.

javascript
1
2
3
4
5
6
7
8
9
10
          // Pure Function
function square(x) {
  return x * x;
}

// Impure Function
let multiplier = 2;
function multiplyByExternal(x) {
  return x * multiplier; // Relies on external state
}
        

Pure Functions Characteristics

Deterministic Output

A pure function will always return the same result for the same inputs, ensuring reliability.

javascript
1
2
3
4
          function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // Always 5
        

No Side Effects

Side effects occur when a function modifies external variables, interacts with I/O, or alters input data.

Pure functions avoid side effects, which makes them easier to test and debug. Example of Side Effects:

javascript
1
2
3
4
          let count = 0;
function increment() {
  count += 1; // Modifies external state
}
        

Pure Alternative:

javascript
1
2
3
          function increment(count) {
  return count + 1; // Doesn’t touch external state
}
        

Pure functions work with immutable data, creating new values instead of modifying existing ones.

javascript
1
2
3
4
5
6
          const user = { name: "Alice", age: 25 };
const updateAge = (user, newAge) => {
  return { ...user, age: newAge };
};
const updatedUser = updateAge(user, 26);
console.log(updatedUser); // { name: "Alice", age: 26 }
        

Why Pure Functions?

  1. 1
    Predictability: Easier to debug and test because you can trust their output.
  2. 2
    Parallelization: Safe to execute in parallel environments as they don’t depend on shared states.
  3. 3
    Reusability: Clean and modular, making them great building blocks for complex systems.