Wednesday, December 19, 2018

Understanding Pure Function In Javascript

In this tutorial, we are going to discuss javascript pure function. These functions are widely used in javascript and we used for some specific purpose.



What Is A Pure Function?

The definition of a pure function is:
  1. The function always returns the same result if the same arguments are passed in. It does not depend on any state, or data, change during a program’s execution. It must only depend on its input arguments.
  2. The function does not produce any observable side effects such as network requests, input and output devices, or data mutation.

I think now you have a question what is observable side effects ? An observable side effect is any interaction with the outside world from within a function. That could be anything from changing a variable that exists outside the function, to calling another method from within a function.

Side effects include, but are not limited to:
  1. Making a HTTP request
  2. Mutating data
  3. Printing to a screen or console
  4. DOM Query/Manipulation
  5. Math.random()
  6. Getting the current time

Advantages of Pure Function :

  1. You can always predict the result of a given function.
  2. Functional programming reduces the line of codes and almost get rid of a loop.(i.e. re-usability)
  3. Testing is always easy because It does not mutate the state of a variable outside of its lexical scope.

Lets see the below example for pure functions :

Pure Function :
function add(a,b){ 
  return a+b ;
}

console.log(add(2,3))

We called this function as pure function because of below reasons :
  • Given the same input, will always return the same output.
  • Produces no side effects.

Impure Function :
function add(a){ 
  return a+ Math.random() ;
}

console.log(add(2))

We called this function as impure function because for the same input, it is returning different output. 

This is all about pure function in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment