1

This is a portion of code from https://bl.ocks.org/mbostock/4183330

I am trying to understand how names.some(function(d)...}) works.

  1. Shouldn't the anonymous function passed to .some() return a conditional statement that "countires" can be evaluated against?

  2. When will names.some(..) return true or false?

  3. Why doesn't d.name = n.name create "name" property in "countries" without "return"?

queue()
    .defer(d3.json, "world-110m.json")
    .defer(d3.tsv, "world-country-names.tsv")
    .await(ready);

function ready(error, world, names) {
    var countries = topojson.feature(world,world.objects.countries).features
    countries = countries.filter(function(d) {
        return names.some(function(n) {
                  if (d.id == n.id) return d.name = n.name;
     });
})
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
user3562812
  • 1,751
  • 5
  • 20
  • 30

1 Answers1

3

1) Since it's using names.some(), the function is testing each element of names, not countries.

2) When any of the names have an id that matches d.id and n.name is not empty.

3) It will always create the property. But if there's no return, .some() doesn't get a truth value that it can evaluate.

It would probably be easier to understand if they'd written:

return names.some(function(n) {
    if (d.id == n.id) {
        d.name = n.name;
        return d.name;
    } else {
        return false;
    }
});

return d.name = n.name; combines the assignment and return value into a single statement. And the code is making use of the fact that functions implicitly return undefined when they don't execute a return statement, and undefined is falsey.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you so much for clarification. I am a bit confused since the code inside .some() does not have a explicit statement "return true". So, returning a variable (d.name) also implies true? Under which topic should I look into to understand this concept? – user3562812 Feb 06 '17 at 21:15
  • 1
    It just cares if the value is *truthy*. Any non-empty string is truthy. – Barmar Feb 06 '17 at 21:16
  • See http://stackoverflow.com/questions/35642809/understanding-javascript-truthy-and-falsy – Barmar Feb 06 '17 at 21:18