0

I am new to javascript and need help figuring out code written by someone else so that I can make some changes.

Passed to this function is a "graph" object consisting of an array of 'nodes' and an array of 'links.'

The first thing that this function does is to define variable "label" as an object with an empty array of nodes and an empty array of links. At this point I expected that doing a console.log of "label" would show two empty arrays, but this is not the case; the console.log shows array elements that I didn't expect would be populated until the next step (the forEach). What is going on here?

Here is the code related to this question:

makeGraph = (graph) => {
var label = {   
    'nodes': [],
    'links': []
};

console.log(label);

graph.nodes.forEach(function(d, i) {
    label.nodes.push({node: d});
    label.nodes.push({node: d});
    label.links.push({
        source: i * 2,
        target: i * 2 + 1
    });
});
}
Joel
  • 1
  • 1
  • Does this answer your question? [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) You might want to read the tooltip of the blue `i` icon saying _“Value below was evaluated just now”_ (i.e. _now, after_ your code has run). – Sebastian Simon Jun 01 '20 at 20:04
  • Use `let` for label (not var). `let label = { 'nodes': [], 'links': [] };` – Denis Stukalov Jun 01 '20 at 20:49

0 Answers0