Pure Vs Impure Functions In Javascript

In this post, we will see the difference between pure functions and high-order functions in javascript.

What are Pure Functions in Javascript?

Functions which does not produce side effect are called pure function. This means that it does not depend on any external variable (like global). Also, it does not modify any external variable.

Such functions always produce the same output for the same input.

Example:- Here doubleNumber() is pure function because its result depends purely on input. It does not produce any side effect.

function doubleNumber(num) {
  return 2 * num;
}

let result = doubleNumber(6);
console.log(result);

What are Impure Functions in Javascript?

Impure functions produce side effects and do not always give the same output for the same input.

Example 1:- Below function is impure because its return value depends on the global variable “val”. Also, it’s modifying variable “val” as a side effect. Even console.log() is considered a side effect.


let val = 3;

function doubleNumber(num) {
  val = 2;
  console.log(val);
  return val * num;
}

let result = doubleNumber(6);
console.log(result);

For more check out:- https://www.freecodecamp.org/news/pure-function-vs-impure-function/

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.