What does the = +_ operator do in JavaScript?
Sample code:
hexbin.radius = function(_) {
if (!arguments.length)
return r;
r = +_;
dx = r * 2 * Math.sin(Math.PI / 3);
dy = r * 1.5;
return hexbin;
};
r = +_;
+
tries to cast whatever _
is to a number._
is only a variable name (not an operator), it could be a
, foo
etc.Example:
+"1"
cast "1" to pure number 1.
var _ = "1";
var r = +_;
r
is now 1
, not "1"
.
Moreover, according to the MDN page on Arithmetic Operators:
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. [...] It can convert string representations of integers and floats, as well as the non-string values
true
,false
, andnull
. Integers in both decimal and hexadecimal ("0x"
-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate toNaN
.
It is also noted that
unary plus is the fastest and preferred way of converting something into a number