# Depth First Traversals of Graphs - recursive call before iteration of next loop

Hello,

I am just trying to wrap my head around this code.
The exercise states ’ We won’t have to worry about iterating through all the neighbors before going down the neighbor’s first connected vertex. This is because the recursive call occurs before the next iteration of the for loop.’ In practice how does this work? Is not the code synchronous, so the entire for Each function completes first so we could end up with 5 neighbours at once for a vertex with 5 edges??

Thank you

const testGraph = require(’./testGraph.js’);

const depthFirstTraversal = (start, visitedVertices = [start]) => {

console.log(start.data);

start.edges.forEach(edge => { //if vertex 1 has 5 edges, why do not all 5 edges pass through?

``````const neighbor = edge.end;

if (!visitedVertices.includes(neighbor)) {

visitedVertices.push(neighbor);

depthFirstTraversal(neighbor, visitedVertices);

}
``````

});

};

depthFirstTraversal(testGraph.vertices[0]);

Actually I think I have answered my own question by comparing it to the Breadth First Traversal on the next slide. In this function, there is no recursive function at all and therefore all the edges are visited. In BFT, the recursive function was ‘part of’ the actual for.each call itself so it was running synchronously by not allowing the next iteration.

const breadthFirstTraversal = (start) => {

const visitedVertices = [start];

start.edges.forEach(edge => {

``````const neighbor = edge.end;

if (!visitedVertices.includes(neighbor)) {

visitedVertices.push(neighbor)

}
``````

});

console.log(visitedVertices)

};