🟨 JavaScript Q16 / 104

What is a pure function?

AI-Powered Answer ✓ Answered

Pure functions are a fundamental concept in functional programming that contribute to more predictable, testable, and maintainable code. Understanding their characteristics is crucial for writing robust JavaScript applications.

What is a Pure Function?

A pure function is a function that satisfies two main conditions: it always produces the same output for the same input, and it causes no observable side effects.

  • Deterministic: Given the same inputs, it will always return the same output.
  • No Side Effects: It does not cause any observable changes outside its local scope (e.g., modifying global variables, DOM, I/O operations).

Determinism

Determinism means that the function's output depends solely on its input arguments. If you call the function with the exact same arguments multiple times, you are guaranteed to get the exact same result every time.

No Side Effects

A side effect is any interaction with the outside world that is observable. Pure functions do not modify any state outside their own scope. This means they won't alter global variables, modify arguments passed by reference, perform I/O operations (like network requests or logging to console), or change the DOM.

Benefits of Pure Functions

  • Predictability: Easier to reason about as their behavior is entirely determined by inputs.
  • Testability: Simple to test as you only need to verify outputs for given inputs, without mocking external dependencies.
  • Memoization/Caching: Their deterministic nature allows caching of results for repeated inputs, improving performance.
  • Concurrency: Can be run in parallel without fear of race conditions or shared state issues.
  • Debugging: Easier to debug because problems are isolated to the function's scope.

Pure Function Example

This function add always returns the sum of its two arguments, and it doesn't change anything outside its scope.

javascript
function add(a, b) {
  return a + b;
}

console.log(add(2, 3)); // Output: 5
console.log(add(2, 3)); // Output: 5 (always the same)

Impure Function Example

This function addToArray is impure because it modifies an array outside its scope. The getRandomNumber function is impure because its output changes each time it's called, even with no inputs.

javascript
let globalArray = [1, 2];

function addToArray(item) {
  globalArray.push(item); // Side effect: modifies globalArray
  return globalArray;
}

console.log(addToArray(3)); // Output: [1, 2, 3]
console.log(addToArray(4)); // Output: [1, 2, 3, 4] (output changes due to mutation)

function getRandomNumber() {
  return Math.random(); // Impure: output is not deterministic
}

console.log(getRandomNumber()); // Different output each time
console.log(getRandomNumber()); // Different output each time