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;
        }
    }
}
10
  • because it has no return statement in it - you also "return" in a .forEach callback, which is pointless, ... perhaps you wanted map instead Commented Mar 8, 2018 at 5:14
  • Where exactly have you declared the varible test? Commented Mar 8, 2018 at 5:15
  • @JaromandaX return test; Commented Mar 8, 2018 at 5:16
  • oh for goodness sake, remove the image, it adds nothing to the question Commented Mar 8, 2018 at 5: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 Commented Mar 8, 2018 at 5:17

1 Answer 1

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.

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

1 Comment

i.e. it's a star trek GNDN ... goes nowhere, does nothing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.