Pure and Impure function in JavaScript

  • In JavaScript, a pure function is a function that always produces the same output for the same input and has no side effects. In other words, it operates only on its input parameters and does not modify any external state or variables outside its scope. Pure functions are essential in functional programming because they make the code easier to reason about, test, and maintain since they have predictable behavior and no hidden dependencies.
To be considered a pure function, a function must satisfy the following criteria:
  • Deterministic: For a given set of input parameters, the function will always return the same output.
  • No side effects: The function does not modify any state outside its scope, such as changing global variables, modifying objects, or making network requests.
Let's see an example of a pure function:


    // This is a pure function
    function add(a, b) {
        return a + b;
    }

    let result1 = add(2, 3); // Output: 5
    let result2 = add(2, 3); // Output: 5 (same input, same output)

  • In the example above, the `add` function takes two parameters, `a` and `b`, and returns their sum. The function is deterministic because the result is solely determined by its inputs. Also, it has no side effects as it does not modify any external state.
  • Now, let's look at an impure function:


    // This is an impure function
    let total = 0;

    function addToTotal(amount) {
        total += amount;
        return total;
    }

    let result3 = addToTotal(5); // Output: 5
    let result4 = addToTotal(3); // Output: 8

  • In this example, the `addToTotal` function takes an amount and modifies the external `total` variable, which exists outside the function's scope. This makes it impure because its behavior depends not only on its input but also on the external state (`total`). Calling this function with the same input can produce different results based on the current value of `total`, making it non-deterministic.
  • To summarize, pure functions are predictable and have no side effects, which makes them easier to test, understand, and maintain. By favoring pure functions, you can write more reliable and maintainable code in JavaScript.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...