JBT
JBT

Reputation: 177

Is This Callback Referencing a Dereferenced Closure?

I have been dealing with issues in multiple pieces of code but it seems to boil down to what I’m showing in this demo. I think it is related to the ’s dereferencing of a closure:

function get_5(callback) {
    var result = 5;
    callback(result);
}

function get_self(x) {
    return x;
}

get_5(console.log);
// 5

console.log(get_self(5));
// 5

In the first result, the first function ran as expected, sending its hidden variable into the input of the console.log function.

The second result also makes sense, as it really just proves the second function works: it takes what was fed in and returns it.

But things get strange when I try to combine the two functions:

var a = get_5(get_self);

console.log(a);
// Undefined!

This third result is undefined, strangely enough, and I am not sure why. Is the closure being dereferenced, maybe to the “sneakiness” of the get_self function? How can I fix this? As a bonus, is there a way to eliminate the get_self function entirely and be able to directly read the variable result, which isn’t modified, without specifying any particular callback?

Upvotes: 0

Views: 48

Answers (1)

Quentin
Quentin

Reputation: 943510

get_5 has no return statement. It doesn't matter what you pass to get_5, it will always return undefined.

Perl will return the result of evaluating the last statement in a sub, but JavaScript will not.

If you want get_5 to return the result of calling the callback you pass to it, then you have to say so explicitly:

function get_5(callback) {
    var result = 5;
    return callback(result);
}

Upvotes: 4

Related Questions