Johnny
Johnny

Reputation: 161

Setting variable to a return from a callback function

getElementId function:

function getIdElements(idname, callback) {
    callback(document.getElementById(idname))
};

I want to use it like this but plLen gets undefined:

var plLen = getIdElements("length", function(e){return e.textContent});

I would love if someone could explain it as deep as possible. Thank you.

Upvotes: 0

Views: 1023

Answers (1)

Kobi
Kobi

Reputation: 138007

You can simply return the value the callback returns:

function getIdElements(idname, callback) {
     return callback(document.getElementById(idname));
}

which is pretty much the same as getting the return value from the callback, and return it. Here's a verbose version:

function getIdElements(idname, callback) {
     var element = document.getElementById(idname);
     var callbackRetrunValue = callback(element);
     return callbackRetrunValue;
}

In your code: with no return value, the value you read from your getIdElements is simply undefined: What does javascript function return in the absence of a return statement?

Upvotes: 4

Related Questions