akhilesh
akhilesh

Reputation: 53

function sent to other functions as arguments

I was reading a book on react and was on functional programming chapter when I encountered this.

const insideFn = logger =>
    logger("They can be sent to other functions as arguments");
insideFn(message => console.log(message))
// They can be sent to other functions as arguments

Now I am quite confused:

  1. The output of insideFn is argument of logger function, just an argument, it is not being returned from logger function. So why is the output of insideFn, argument of logger?
  2. I tried to check the type of message - result was string. Why is it string? isn't message a function?
  3. I expected when we do console.log of message it should return function definition of logger, but it returns its argument? This doesn't make sense to me?

Thank you for explaining.

Upvotes: 1

Views: 114

Answers (1)

Bergi
Bergi

Reputation: 664385

The arrow functions make this a bit confusing. Maybe a more verbose example would be clearer:

function insideFn(logger) {
    logger("inside's log message");
    // some computation here
    return 42;
}

function myLogger(message) {
    console.log(message);
}
insideFn(myLogger);

Upvotes: 3

Related Questions