0

I've been exploring examples on bl.ocks.org in an effort to learn D3 and keep coming across this + notation below. Google searches have been unfruitful in explaining what it is used for, I assume because I'm still learning the D3 and Javascript jargon.

What does the + do in the code snippet below? This code is from this bl.ocks example.

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;
  • This question is another proof how tricky code is worse than boring code: `Number(svg.attr("width"))` wouldn't raise questions. – zerkms Jul 06 '17 at 00:20
  • 1
    @zerkms Very true. But now that I am familiar with this idiom, it shouldn't trip me up again. – Nathaniel Rivera Saul Jul 06 '17 at 00:21
  • Hopefully you personally would prefer `Number(variable)` though :-) – zerkms Jul 06 '17 at 00:22
  • I'm not sure. Reading more of the question that this was marked as a duplicate of, it sounds like `+` is the preferred way to convert to a number. I imagine it's something similar to `++` rather than `+=1` in many languages. So the question is, is it better to be idiomatic or better to be explicit? – Nathaniel Rivera Saul Jul 06 '17 at 00:29
  • It totally is not "preferred". It just a hack that conveniently allows you to reach the same result as the specifically designed `Number` function. It's totally not "idiomatic" either. The same way - if you need to multiply an integer by `2` - you `* 2`, not `<< 1` (they are equivalent) – zerkms Jul 06 '17 at 00:30
  • To be fair it is very common to see `+` used like that in d3 projects/examples. Not saying that's the way it should be, but I think it would be difficult to learn d3 without knowing what the `+` is doing. – DonovanM Jul 06 '17 at 01:01

0 Answers0