Higher Order Function & Pure Functions in JavaScript.

Higher Order Function & Pure Functions in JavaScript.

ยท

2 min read

Hi ๐Ÿ‘‹, I'm back again. In this blog, we are going to talk about Higher Order Functions as well as pure functions in JavaScript.

What is Higher Order Function?

Higher Order Functions are the functions in JavaScript that either takes a function as an argument or/and return a function as an output.

In simple words Higher Order Functions completely operate on another function. Either having another function as an argument or as a return value;

Example

function sayGoodMorning(){
  console.log("Good Morning Mate!");
}

function letsGreet(sayGoodMorning){
  sayGoodMorning();
}

letsGreet(sayGoodMorning);

In the above code snippet, we have a normal function "sayGoodMorning" and "letsGreet". The difference between these two is that "sayGoodMorning" is a normal function whereas the "letsGreet" function is a Higher Order Function. Let's see why

As discussed earlier the higher order function either takes a function as an argument or returns the function.

In "letsGreetFunction" we are passing the "sayGoodMorning" function as an argument. Which fulfills the definition of a higher order function.

Pure Functions

A pure function is a block of code that will always return the same value if you pass the same arguments to it every time.

Pure function has the following properties

  1. The pure function should only work with its own arguments.
  2. It doesn't cause any sort of side effects because it does not mutate any state or data.

Code Example

function calculateTip(bill){
  return bill + bill * 0.15;
}

console.log(calculateTip(100));

In the above code snippet, calculateTip is a pure function because if you provide the same bill amount to it everytime you call it, you are going to have the same amount every time. Also, it is not changing any data outside of its scope.


I hope I was able to deliver something good to you guys โ˜บ. Feedbacks, suggestions, etc are always welcomed.

Have a fun and safe time and Thank you so much for dedicating your time to go through this blog โค.

Let's Learn and Grow Together. Adios amigos/amigas hasta la proxima vez ๐Ÿ’œโ˜•