Search code examples
javascriptnode.jsfor-in-loop

why i get function while iterating with for in loop in node.js


i am iterating an array of objects using for in loop i am getting all the objects inside it but i also get a function and i am wondering how i get this. my iterating code looks like :

 for (var key in student) {
        console.log(student[key]);
 }

what i get along with objects is

 function (value) {
    if (this.indexOf(value) !== -1) {
        this.splice(this.indexOf(value), 1);
        return true;
    } else {
        return false;
    }
}

which is creating problem in throwing error even if i simply use

console.log(student[key].length);

any opinions are highly appreciated.


Solution

  • Because for-in loops visit all enumerable properties on the object and its prototypes, including those that refer to functions. Apparently, someone has added an enumerable property to the student array (or Array.prototype) that refers to a function.

    If you want it not to show up, make the property non-enumerable via Object.defineProperty, or if it's on the object's prototype chain but not the object itself and you only want the object's "own" properties, add a hasOwnProperty check (or use Object.keys to get an array of property names).

    But if student is really an array, for-in is usually the wrong tool for looping through its entries; see the answers to For-each over an array in JavaScript? for details.


    In a comment you've asked:

    when i use nested forEach loop it suggest me dont use function inside loop what to do in that case sir?

    That warning isn't always important and sometimes (even often) you can just ignore it. But if you want to avoid creating functions in loops, just move the function out of the loop. For instance, you can turn this:

    function foo() {
        outer.forEach(function(outerEntry) {
            outerEntry.forEach(function(innerEntry) {
                // Use `innerEntry` here...
            });
        });
    }
    

    into

    function foo() {
        outer.forEach(handleOuter);
    
        function handleOuter(outerEntry) {
            outerEntry.forEach(handleInner);
        }
    
        function handleInner(innerEntry) {
            // Use `innerEntry` here...
        }
    }