6Michael6Myers6
6Michael6Myers6

Reputation: 29

Passing A Function As Argument To A Function

function say(something) {
  console.log(something);
}

function exec(func, arg) {
  return func(arg);
}

exec(say, "Hi, there.");

Why does this code work? I feel like it shouldn't since what is in the second function should return

say(something) (arg) { 
  console.log(something) ; 
}

Upvotes: 0

Views: 51

Answers (3)

ADyson
ADyson

Reputation: 62069

It works as it does because when you write return func(arg);, the func(arg) bit executes the function. What is returned is then the result of executing func(arg).

However, you're right that say() doesn't actually return a value, it just logs to the console within that function. The output you're seeing is the result of that log command. If you logged the returned value instead you'd see undefined as the result.

But if you'd passed a different function to exec which did return a value, then you'd need the return in exec() for it to work properly.

P.S. I'm not sure if this is part of what you're asking, but the difference between that and when you wrote exec(say, "hi there"); is that in that code, say is a reference to the "say" function. At that moment it's treated like any other variable, just the same as if you passed in a number or a string, for example.

The difference is the (), which causes the function to be executed, rather than passed as a reference.

In the question you seem to imply that you'd expect the source code of the say() function to be displayed, but this is not what it does, and also is not possible anyway.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386786

Maybe you are looking for a closure, where exec returns a function for getting arg for the first handed over function func.

function say(something) {
    console.log(something);
}

function exec(func) {
    return function (arg) {
        return func(arg);
    };
}

exec(say)("Hi, there.");

Upvotes: 1

Grzesiek Danowski
Grzesiek Danowski

Reputation: 467

Function say returns undefined (default value if no return keyword is used), and therefore function exec also returns undefined.

Proof:

function say(something) {
  console.log(something);
}

function exec(func, arg) {
  var result = func(arg);
  console.log(result);
  return result;
}

var result2 = exec(say, "Hi, there.");
console.log(result2);

Upvotes: 1

Related Questions