0

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.

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

5 Comments

Great but I would like to know why the mine version is not working as I expected.
@Johnny: Because you don't return the value that callback returns. You simply ignore callback's return value.
True but I am returning that from an other function inside getIdElements shouldn't both close with the value I've returned inside?
@Johnny: No, of course not. That would mean you could always only call one function inside another function. Imagine there are two functions foo and bar. You know what they are doing but you don't know if they return a value. Now you have a function function baz() { foo(); bar(); }. According to your logic, if foo returned a value, baz would return that value too and bar would not even be executed. That's quite unintuitive. It would mean you'd always have to know how a function is implemented, which completely defeats creating a function for abstraction in the first place.
@Johnny - No: return is working for the current function. The only thing that works like you describe is throwing an exception. There are languages that "automatically" return the last value, but JavaScript isn't one of them (examples are CoffeeScript, or Scheme).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.