javascript - Function with forEach returns undefined even with return statement -


i'm making function checking value of in object array, reason keeps returning undefined. why that?

demo: http://jsfiddle.net/cnywz/1/

var data = [{     "key": "1111-1111-1111",         "email": "test@test.com" }, {     "key": "2222-2222-2222",         "email": "test@boo.com" }];   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 function, you're returning function passed foreach, not getbykey.

you adapt :

function getbykey(key) {         var found = null;     data.foreach(function (val) {         if (val.key === key) {             found = val;         }     });     return found; } 

but iterate on elements, if item found. that's why you'd better use simple for loop :

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

note adapted code return value, not key. suppose intent. might have been confused iteration function : first argument passed callback give foreach element of array.


Comments