Function with forEach returns undefined even with return statement

I'm just making a function for checking a value of something in my object array, but for some reason it keeps returning undefined. Why is that?

Demo: http://jsfiddle.net/cNYwz/1/

var data = [{
    "Key": "1111-1111-1111",
        "Email": "[email protected]"
}, {
    "Key": "2222-2222-2222",
        "Email": "[email protected]"
}];


function getByKey(key) {    
    data.forEach(function (i, val) {
        if (data[val].Key === key) {
            return data[val].Key;
        } else {
            return "Couldn't find";
        }
    });
}

var asd = getByKey('1111-1111-1111');
console.log(asd);

In your function, you're returning from the function passed to forEach, not from getByKey.

You could adapt it like this :

function getByKey(key) {    
    var found = null;
    data.forEach(function (val) {
        if (val.Key === key) {
            found = val;
        }
    });
    return found;
}

But this would iterate over all elements, even if the item is immediately found. That's why you'd better use a simple for loop :

function getByKey(key) {    
    for (var i=0; i<data.length; i++) {
         if (data[i].Key === key) {
            return data[i];
        }
    }
}

Note that I also adapted your code to return the value, not the key. I suppose that was the intent. You might also have been confused with another iteration function : the first argument passed to the callback you give to forEach is the element of the array.


Your function getByKey has no return statement. The two returns are for the anonymous function used by forEach.


You're not returning anything to the outer scope, try this alternative:

function getByKey(key) {    
  var result = data.filter(function (i, val) {
    return data[val].Key == key;
  });
  return result.length ? result : 'Not found';
}

Try storing the positive result as a variable, and then returning that variable (or a "Couldn't find" in case nothing is written) at the end of the function after the forEach loop.

function getByKey(key) {    
    var result;

    data.forEach(function (val, i) {
        if (data[val].Key === key) {
            result =  data[val].Key;
        }
    });

    return result || "Couldn't find";
}