Pure functions in JavaScript

Pure functions in JavaScript

ยท

2 min read

Pure functions are a part of functional programming paradigm

Why pure functions?

  • Clean code
  • Easy to test and debug
  • Decoupled and independent from the program so that we could use this as a utility function

Rules:

  • A pure function should always have at least one parameter otherwise they are same as constants
    const name = "Bipul";
    console.log(name);
    //same as a constant
    const firstName = () => "Bipul";
    console.log(firstName());
    
  • Same input always gives same output

  • We can replace the functions with the output which is called referential transparency.

For example:

const getFullName = (firstName, lastName) => `${firstName} ${lastName}`;

//referncial transperency
const myFullName = getFullName("Bipul", "Sharma")

console.log( `My name is ${myFullName}`); //My name is Bipul Sharma
  • No side effects

This means:

No accessing scope outside the function
No accessing database, API, filesystem, storage, etc
No modifying DOM
No console logging
No input could be mutated, all input to be immutable

  • A pure function always returns something

Examples:

// Here we are accessing z(present in the global scope) 
//This is completely fine in javascript 
//But this makes the multiply function impure
const z = 5;
const multiply = (x, y) => x * y * z;
const ans = multiply(1, 2);
console.log(ans); //10

//Here we are mutating the value of num
//Also referencing num from outside the scope of the function impureMultiplByTen . 
let num = 10;
const impureMultiplByTen = () => num*=10;
console.log(impureMultiplByTen ())//100
console.log(num)//100

//Converting this to a pure function
const pureMultiplyByTen = (num) => num*10
console.log(pureMultiplyByTen(num))//100
console.log(num)//10

//Again here we are mutating myFavFoods
let myFavFoods = ["Anything with lots of cheese", "Panner items with NaaN"];
const impureAddToMyFavFoods = (myFavFoods, moreFood) => {
  myFavFoods.push(moreFood);
  return myFavFoods;
};
console.log(impureAddToMyFavFoods (myFavFoods, "Kadai Chicken"));
 //["Anything with lots of cheese", "Panner items with NaaN", "Kadai Chicken"]
console.log(myFavFoods);
//["Anything with lots of cheese", "Panner items with NaaN", "Kadai Chicken"]

//Converting this to a pure function
const pureAddToMyFavFoods = (myFavFoods, moreFood) => [...myFavFoods, moreFood]
console.log(pureAddToMyFavFoods())
//["Anything with lots of cheese", "Panner items with NaaN", "Kadai Chicken"]
console.log(myFavFoods)
//["Anything with lots of cheese", "Panner items with NaaN"];

// Some pure higher order functions
const numbers = [2, 4, 6, 8, 10];

const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); //[2, 4, 6, 8, 10]

const halfed = numbers.map((num) => num / 2);
console.log(halfed); // [1, 2, 3, 4, 5]

const add = numbers.reduce((acc, val) => acc + val, 0);
console.log(add); //30

console.log(numbers); //[2, 4, 6, 8, 10]

Happy Coding ๐Ÿš€

ย