JavaScript Interview Question : Explain JavaScript Currying with Example

Recently I am preparing a question bank for interviewing JavaScript Engineers for my Clients. Most commonly asked Questions in Intermediate JavaScript is about Currying and Higher Order Functions.

So, What are they? Lets start them one by one.

Have you come accross javascript function calling with two parenthesis?

ColorAndRotateBox("red")("180deg");

Suppose we want apply Red color and rotate transform of CSS to the <div> element.

<div class="box">
What is JavaScript Currying?
</div>

check the following code

ColorAndRotateBox = (color) => {
    var obj = document.querySelector(".box");
 	obj.style.color = color;
  return (deg) => {
  	 obj.style.transform = `rotate(${deg})`;
  }
}

If you run above code, It will output as follow

So what happened here?

Our function took color as an argument and applied to <dom element> and later returned another function to rotate div.

So, basically curring is function take 1st argument, do maniplutation on it and later return another function by passing 2nd argument to it. Very simple explanation is follow.

function multiply (a) {
  return function (b) {
    return a * b;
  }
}

Above function is multiplication of two number using JavaScript Curring.

multiply(5)(6) // answer : 30

What about Higher Order Functions then?

I will write in much detail about higher order functions in JavaScripts. But inshort, Higher Order Functions in JavaScript take functions as argument and may or may-not curry them.

In above curring function, could rewritten as higher order function as follow.

function ColorAndRotateBox(color, callBack) {
    var obj = document.querySelector(".box");
 	obj.style.color = color;
      callBack();
}


ColorAndRotateBox("red",function(){
    degFunc("180deg");
});


degFunc = (deg) => {
   var obj = document.querySelector(".box");
   obj.style.transform = `rotate(${deg})`;
}

 

Total
0
Shares
Leave a Reply

Your email address will not be published.

 
Previous Post

How to enable dark mode in shopify admin even before they release that feature in 2022

Next Post

Technical SEO – How to Build Web Vitals friendly Carousel Slider

Related Posts