How does a higher order function pass argument to a function that is an argument? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How does a higher order function pass argument to a function that is an argument?

// add zero paddings to a min value of an array function zeroPaddingToMin(min, width) { return (...args) => { let result = zeroPad(min(...args), width); return result; } } // add zero paddings to a number function zeroPad(number, width) { let string = String(number); while(string.length < width) { string = '0' + string; } } console.log(zeroPaddingToMin(Math.min, 3)(22, 14, 17)); // 014 /* I am not too sure about the syntax used in the last statement. Math.min() method is passed as an argument to the zeroPaddingToMin() function. What I am not sure about is the parentheses (extra arguments) that comes after the zeroPaddingToMin() function. My hypothesis is that it is a way to pass arguments to returning function but I am not very sure. How does it works? I am a beginner in Javascript programming. */

4th Nov 2020, 3:34 AM
Logos
Logos - avatar
2 Answers
+ 7
zeroPaddingToMin returns a nameless lambda function that has a variable list of arguments. The (22, 14, 17) calls that function with a list of those three numbers. The lambda selects the minimum number from the list of 14 to call the zeroPad function to add the needed leading zeroes to make the string of three characters at least.
6th Nov 2020, 5:08 AM
John Wells
John Wells - avatar
+ 2
John Wells Thank you very much Sir. I have a better understanding about it now.
9th Nov 2020, 3:49 AM
Logos
Logos - avatar