Search code examples
javascriptjavascript-objectsfor-in-loop

Accessing properties from object in `for`–`in` loop results in `undefined`


I have these two classes:

class Node {
    constructor(nodeId){
        this.nodeId = nodeId;
        this.adjacencies = [];
    }

    connectToNode(nodeToConnectTo){
        this.adjacencies.push(nodeToConnectTo);
    }
}

class Graph{
    constructor(nodes){
        this.nodes = nodes;
    }

    printGraph(){
        for (let node in this.nodes){
            console.log(node.nodeId);
        }
        
    }
}

I’m simply trying to call printGraph to print all the nodeIds this way:

let node1 = new Node('1');
let node2 = new Node('2');
let node3 = new Node('3');
const arr = [node1, node2, node3];
let graph = new Graph(arr);

graph.printGraph();

But it’s printing undefined. I can’t seem to figure out why it isn’t simply printing the nodeId.


Solution

  • you are using the wrong for loop. Try changing it to:

    printGraph(){
      for (let node of this.nodes){
        console.log(node.nodeId);
      }   
    } 
    

    A for..of loop should loop over the node the way you want.
    Result:

    1
    2
    3