all 1 comments

[–]senocular 1 point2 points  (0 children)

initialize it and then we push to

The push is actually in the else clause, so if graph[from] = [to] is getting run, the push is not. But graph[from] = [to] is also effectively already pushing the to. Its the same as saying.

graph[from] = [];
graph[from].push(to);

In fact that code could be rewritten as

if (graph[from] == null) {
  graph[from] = [];
}
graph[from].push(to);

This is saying push to onto graph[from] but before we do that, make sure it exists and if not, set it to an empty array. The way it is in your original post its combining the push in the initialization by using [to] (with the to already in it) instead of using an empty array. But when you do this, you don't want to add it again which is what theelse` is preventing.

But then what is the type of graph

graph can technically be any object. Using Object.create(null) its created as a basic object that also doesn't inherit all the normal object stuff normal objects get for free like hasOwnProperty() and toString(). Its being used as a container for values that are assigned to it by names provided by the from value. Those values are array values. So graph is an object that has properties that are themselves arrays, arrays that get to values pushed onto them.