I am trying to understand how can we achieve such a function in JS, and what is the main use of this approach?
multiple(5) will return 5 multiple(5)(6) will return 30
how can we achieve such a function in JavaScript?
I am trying to understand how can we achieve such a function in JS, and what is the main use of this approach?
multiple(5) will return 5 multiple(5)(6) will return 30
how can we achieve such a function in JavaScript?
You can use valueOf
and function that return a function.
Here: multiple(5)
will return 5 multiple(5)(6)
will return 30
function multiple(x){
function func(y){
return x*y
}
func.valueOf=function(){return x}
return func
}
See this JSFiddle: https://jsfiddle.net/k9meraL6/
alert(multiple(5)(6)) //30
alert(multiple(5) + 1) //6
JavaScript calls the valueOf method to convert an object to a primitive value
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf