Tech Incent
JavaScript Snippets Others

Pure function in javascript

pure-function-in-javascript

A pure function is a function that has no side effects. Its function always returns exact same thing every single time you gave a single input. So every single time you give the same input it always returns the same output. and it affects nothing it means it will not manipulate value outside of the scope.

Pure function follow two rules

  1. Give the same input it must return same output which is predictable
  2. The function is no side effects
Example #1. Not pure funciton
const array = [1, 2, 3, 4];

function addItemToArray(arr, item) {
  // Return someting
  // Different everytime
  // Mutates/side effect the array variable
  arr.push(item)
}

addItemToArray(array, 5)
console.log(array)

// Output
// [ 1, 2, 3, 4, 5]
Example #2. Pure Function
const array = [1, 2, 3, 4];

function addItemToArray(arr, item) {
  // Predictable result
  // No mutations
  return [...arr, item]
}

console.log(addItemToArray(array, 5))

// Output
// [ 1, 2, 3, 4, 5]

Example #1 Not pure Function: this function is only depend in input an array and a item. So you might think it’s okay it’s pure function right. because only take input and create output. But again problem is that this actually has a side-effect. It’s changing the array global variable output. So with pure function, you never want to change the input you added into the element

Example #2 Pure Function: This function returns a new array, nothing changes in the array item. this function has no external state, only takes input and gives an output. It does not change the array which is a global variable. because it creates a new array

Below are some cases or functions has limitation you can’t create pure funciton.

  • Mutating data
  • Making a HTTP request
  • Math.random()
  • DOM Query/Manipulation
  • Getting the current time

Related posts

Start Million Dollar Business with fiverr

Tech Incent

Everything You Need to Know About Man in Suit

Tech Incent

What is blog?

Tech Incent