A little help with higher order functions

Hello everyone, please could someone help me in understanding higher order functions? I’m having a quite hard time solving this problem

function two(){}
function three(){}
function multiply(){}
two(multiply(three())) //=> 6

I’ve tried for a while and still I cannot figure out how I should write a function in a way that will output the above result. Please provide some explanation and, if possible, links or other material to better understand the concept of a higher order function…

Hello there,

This is a very weird functional procedure, but if you are sure this is what you want to solve exactly that, then let us split up what needs to be done in words:

  • Presumably, three() needs to return the number 3
  • multiply will accept one argument, and return a function which also accepts one argument, and returns the product of its argument and multiply's argument.
  • two should accept a function as an argument, and return the output of calling this function with an argument of 2.

I am not really sure what external resources to link. So, I suggest you look into callback functions. I would not say that this example is particularly related to higher order functions.

Hope this helps

I have a grasp of how is possible to play with callbacks, at least of the basis.

//Example 1
function outer(x = 20) {
  let example = 20
  function inner() {
    return example * x
   } return inner()

  outer(10) // 200
outer() // 400 (because of x's default value of 20)

//Example 2
let little = a => a + 1
let bigger = b => b * 10
let evenBigger = x => x
evenBigger(bigger(little(9))) // 100

//Example 3
function fun(x) {
  let random = x * 10
  function moreFun() {
    return random * 10
  } return moreFun()
fun(10) // 1000

//Example 4
function A(x) {
  return function B(y) {
     return function C(z) {
      console.log(x + y + z);
A(1)(2)(8); // logs 6 (1 + 2 + 8) (could put whatever number I want)

I know my first example isn’t accurate to depict the concept of higher order functions, but is a challenge I’d like to resolve. It’s not that hard to chain three different functions, but having it working as in the first case seems much harder to me

The initial problem really lacks one more line to understand the topic and challenge itself better. Should be this way in my opinion:

function two(){}
function three(){}
function multiply(){}
two(multiply(three())) //=> 6
three(multiply(two())) //=> 6

This way whole picture makes much more sense to me. Combine this :point_up: with suggestions from @Sky020 and you’ll nail it!