3

I'm new to Javascript, and I am using d3.js for visualizations. I know about operator meanings and concatenation, and have read that the + sign can perform changing the right-hand operand to the + sign to a numeric value, however I'm stumped on what the line gravity = +x; in force.gravity is doing since x is already a numeric value (already an integer). I have tested with negative and positive numbers and it seems to just return the value I pass through the x, I do get past the if statement for my uses. Whereas, if I use -x then it will change the sign. Can anyone explain what is going on with the +&- and why the function is basically just returning what I pass.

force.gravity = function(x) {
  if (!arguments.length) return gravity;
  gravity = +x;
  return force;
};
dlchang
  • 677
  • 7
  • 13
  • 1
    `+x` where `x` is a number does exactly what it does when `x` is a string -- convert it to a number. The result of a number converted to a number is that same number. – Lars Kotthoff Aug 06 '15 at 22:53
  • Ah, Thank you for the explanation Lars. I guess I was looking into it too much. – dlchang Aug 10 '15 at 21:14

1 Answers1

4

It causes the object passed in, x, to be converted to a number. If a string is passed in it will attempt to convert it to a number before setting gravity.

For example, calling force.gravity('1'); will have the same result as calling force.gravity(1);.

See javascript: plus symbol before variable.

Community
  • 1
  • 1
lhoworko
  • 1,161
  • 1
  • 14
  • 24
  • I posted that I knew that it did that conversion already, and that x is already a numeric value(int not a string). Maybe I should have clarified that part. – dlchang Aug 06 '15 at 21:55