Pure vs Impure Functions in JavaScript

 
pure function vs impure function in javascript, examples of pure and impure functions, example of pure function, pure vs impure functions react, impure function example

Pure Function

Pure functions always return the same result even the same arguments. It doesn't check any type of information during the execution. It depends only on arguments when it is included.

Here is the Example of the Pure Function:


function Multiplication(a) {
    return a * a;
 }


Impure Function

Any function that changes the arguments and value of the external variable is impure. Let's see the example to get more clear.

Here is the example of Impure Function


function Multiplication(variables){
    var len = variables.length;
    for (var i = 0; i < len; i++) {
      variables[i] = variables[i] * variables[i];
    }
    return variables;
  }


Pure Function vs Impure Function

Pure Function

  • Pure Function is Predictable Function.
  • Pure Function has no side effects.

Impure Function

  • Pure Function is an Unpredictable Function.
  • Pure Function has some side effects.

Predictable(Pure Function)

Now let's see the example to get completely understand.


function addition(a,b){
    return a + b;
}
console.log(addition(5,5))
// Output is 10


Let's predict two numbers between 1 to 10:


function addition(a,b){
    let rand = Math.random() * 10;
    return a + b + rand;
}
console.log(addition(5,5))
// Output is still 10


Side Effects of Impure Function

Let's start with an example:


var number = 5;
function add(a,b){
    return a + b + number;
}
console.log(add(5,5));
// Output is 10


Here, you predict any number which will not add to the sum(Its side effect of this function) because it is changing a variable outside of the function scope.

Thanks For Reading and also read for articles given below...

Read More:: 4 Tips for JavaScript 2021 to write optimized code

Read More:: 7 Best Array Methods In JavaScript 2021

Post a Comment

Previous Post Next Post