Table of Contents

  1. Functions
  2. Pure Functions
  3. Side Effects
  4. Example
  5. Why is it important?

Let’s explore what pure function is 👇

Functions?

Function is a execution of a task. It receives input and returns a value.

Pure Functions

What is a pure function?

  • A function always returns same output if it is passed constant parameters. It doesn’t depends on any state or data, it just depend on its input parameters.
  • This function does not have any effect on other objects, such as requests, input, output or data mutations.

Side Effects

Side Effects are interactions to outside the function. That can be anything from changing a variable that exists outside of a function, to calling another function from within a function. Common side effects:

  • HTPP Request
  • Print data to console
  • Interact DOM
  • Math.ramdom()
  • Get current date time

Example

An example of a function calculating the product price

function priceAfterTax(productPrice) {
 return (productPrice * 0.1) + productPrice;
}

This function isn’t dependent on external variables and doesn’t produce side effects, so it’s a pure function.

Another example

var tax =  10;

function calculateTax(productPrice) {
 return (productPrice * (tax/100)) + productPrice; 
}

This function is dependent on an external variable, so it isn’t a pure function.

Why is it important?

Pure function is used a lot in functional programming. It is useful for testing and refactoring. Because it always returns same outputs with same inputs, testing becomes easier. Besides, it doesn’t affects external environment, so refactoring becomes more convenient. In conclusion, pure functions will help improve the quality of code, make clean code, and be easy to maintainance.