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.

Johnny
  • 161
  • 3
  • 11

1 Answers1

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?

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • Great but I would like to know why the mine version is not working as I expected. – Johnny Aug 20 '13 at 10:48
  • @Johnny: Because you don't return the value that `callback` returns. You simply ignore `callback`'s return value. – Felix Kling Aug 20 '13 at 10:48
  • True but I am returning that from an other function inside `getIdElements` shouldn't both close with the value I've returned inside? – Johnny Aug 20 '13 at 10:50
  • 1
    @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. – Felix Kling Aug 20 '13 at 10:51
  • 1
    @Johnny - No: return is working for the current function. The only thing that works like you describe is [throwing an exception](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw). There are languages that "automatically" return the last value, but JavaScript isn't one of them (examples are [CoffeeScript](http://coffeescript.org/), or Scheme). – Kobi Aug 20 '13 at 10:51