Why does this forEach return undefined when using a return statement

I realize this is an old question, but as it’s the first thing that comes up on google when you search about this topic, I’ll mention that what you’re probably looking for is javascript’s for.. in loop, which behaves closer to the for-each in many other languages like C#, C++, etc…

for(var x in enumerable) { /*code here*/ }

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for…in

http://jsfiddle.net/danShumway/e4AUK/1/

A couple of things to remember :

  • for..in will not guarantee that your data will be returned in any particular order.
  • Your variable will still refer to the index, not the actual value stored at that index.
  • Also see below comments about using this with arrays.

edit: for..in will return (at the least) added properties to the prototype of an object. If this is undesired, you can correct for this behavior by wrapping your logic in an additional check:

for(var x in object) {
    if(object.hasOwnProperty(x)) {
        console.log(x + ": " + object[x]);   
    }
}

Leave a Comment