JavaScript Interview Question : Explain JavaScript Currying with Example

JavaScript Interview

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

What is Curring in JavaScript?

Have you come across JavaScript function calling with two parentheses?

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

Suppose we want to 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 the above code, It will output as follows

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 manipulation 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 numbers 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 have rewritten as higher-order function as follows.

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. Required fields are marked *

 
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