I'm a javascript newbie, and I can't figure out why the variable o
exists in the following code:
var data = [ {"name":"alice", "group":1}, {"name":"bob", "group":2} ];
function getGroup(n) { return n.group; }
function network(nodes, index) {
var gc = {};
nodes.forEach(function(n) {
var i = index(n), o;
if (condition) {
o = gc[i] || (gc[i] = {x:0,y:0,count:0});
o.x += n.x;
o.y += n.y;
o.count += 1;
}
});
}
var net = network(nodes, getGroup)
It seems to me that the iterator in the network
function would be better written this way:
function network(data, index) {
var gc = {};
nodes.forEach(function(n) {
var i = index(n);
if (condition) {
gc[i] = gc[i] || (gc[i] = {x:0,y:0,count:0});
gc[i].x += n.x;
gc[i].y += n.y;
gc[i].count += 1;
}
});
}
I think the second loop is equivalent and it eliminates a variable (and it's easier for me to read). Is the first version following some recommended practice in javascript? I can imagine that it would be good practice to have var o;
inside the iterator to reduce its scope, but in this case o
only refers to an object that's already referenced by gc[i]
. Why not just eliminate it?