0

Why is this function returning undefined? It has a value inside the function, but once I try to assign it to a new variable, it comes back as undefined.

function getLookupDefault(lookupModel) {
    Object.keys(lookupModel.LookupValues).forEach(function (key) {
        if (lookupModel.LookupValues[key].IsDefault == true) {
            test = lookupModel.LookupValues[key].Name;
            console.log("test: " + test);
            return test;
        }
    })
};

var tst = getLookupDefault(model.LookupValuesDelimiter);
console.log("tst: " + tst);

Edit: Thank you. Coming from c#, this was not obvious to me. I have edited the code to this and it works correctly.

function getLookupDefault(lookupModel) {
    for (var key in Object.keys(lookupModel.LookupValues)) {
        if (lookupModel.LookupValues[key].IsDefault == true) {
            test = lookupModel.LookupValues[key].Name;
            console.log("test: " + test);
            return test;
        }
    }
}
  • because it has no return statement in it - you also "return" in a .forEach callback, which is pointless, ... perhaps you wanted `map` instead – Jaromanda X Mar 08 '18 at 05:14
  • Where exactly have you declared the varible test? – Innocent Criminal Mar 08 '18 at 05:15
  • @JaromandaX `return test;` – Scott Marcus Mar 08 '18 at 05:16
  • oh for goodness sake, remove the image, it adds nothing to the question – Jaromanda X Mar 08 '18 at 05:16
  • @ScottMarcus - yes, well spotted, but where is there a return in the `getLookupDefault` function? and returning a value from a forEach callback does nothing anyway – Jaromanda X Mar 08 '18 at 05:17
  • @ScottMarcus He uses it on the `forEach` block which is useless. – wisn Mar 08 '18 at 05:17
  • @JaromandaX You edited your comment. Your original comment made it seem like you didn't see any `return` in the code. – Scott Marcus Mar 08 '18 at 05:17
  • the edit does not change the first part of that comment ... `getLookupDefault` still has no return statement in it – Jaromanda X Mar 08 '18 at 05:18
  • I don't know if either of those duplicates is actually what OP is trying to do here. I think they're actually looking for a way to break out of a `forEach` loop with a `return` like you can do with a normal `for` loop in most languages. – SCB Mar 08 '18 at 05:22
  • If that is the case, [this answer here](https://stackoverflow.com/a/32101207/1112586) might be more like what they're looking for. – SCB Mar 08 '18 at 05:26

1 Answers1

1

That return statement you have in there doesn't return a value to the outer function, it only returns a value to the inner function called by forEach.

kshetline
  • 12,547
  • 4
  • 37
  • 73