Pure and Impure functions in Javascript

 

  • What is a pure function in javascript?
    A function is called pure if it satisfies two conditions –
    1. The function should only be dependent on input parameters

    2. The function should not produce any observable side effects
  • Observable side effects can be
    1. Logging on screen or document
    2. Mutating data
    3. Making network call
    4. DOM manipulation
    5. Math.Random
    6. Getting current time
  • Examples of Pure and Impure functions
    1.
    2.
    3.
    4.
  • Importance in Javascript
    Not all functions need to be, or should be, pure. We can mix pure and impure functions as per our requirements.

    Pure functions are heavily used in functional programming in javascript. React, Redux and other javascript libraries are using pure functionality.

  • Benefits of Pure functions
    1. No side effects
    2. Testable
    3. Maintainable

Leave a Reply

Your email address will not be published. Required fields are marked *