This question already has an answer here:
- variable declaration conditional syntax 3 answers
I'm relatively new to JavaScript and d3, but I'm really interested in force-directed layouts. In Mike Bostock's force-directed visualizations, he tends to parse nodes from a list of links using the following code (or similar):
var links = [
{source: "A", target: "B"},
{source: "B", target: "C"},
{source: "C", target: "A"}];
var nodes = {};
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
I completely understand what he ultimately accomplishing here, I just want to understand the JavaScript syntax in the forEach
loop better (actually, at all). If someone could explain, I'd really appreciate it.
It's obviously very elegant code, but I can't find an explanation anywhere on the internet - I'm probably missing a key term in my searches, so I'm reluctantly asking the question here. What is really throwing me off:
- What the two assignments on either side of the
||
do , - The order of the first assignment of each line (left-hand side of each
||
): why is itlink.source = nodes[link.source]
notnodes[link.source] = link.source
, for instance.