0

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?

joseph oun
  • 135
  • 1
  • 7
  • 5
    Hint: `multiple` will return a function – John Dvorak Feb 11 '18 at 12:00
  • Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Feb 11 '18 at 12:03
  • 4
    "currying" is the keyword for you. – oniondomes Feb 11 '18 at 12:04

1 Answers1

1

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

More info:

Valueof

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

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117