What does = +_ mean in JavaScript
r = +_;
-
+
tries to cast whatever_
is to a number. -
_
is only a variable name (not an operator), it could bea
,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
It is not an assignment operator.
-
_
is just a parameter passed to the function.hexbin.radius = function(_) { // ^ It is passed here // ... };
On the next line
r = +_;
+
infront casts that variable (_
) to a number or integer value and assigns it to variabler
DO NOT CONFUSE IT WITH +=
operator
=+
are actually two operators =
is assignment and +
and _
is variable name.
like:
i = + 5;
or
j = + i;
or
i = + _;
My following codes will help you to show use of =+
to convert a string into int.
example:
y = +'5'
x = y +5
alert(x);
outputs 10
use: So here y
is int 5
because of =+
otherwise:
y = '5'
x = y +5
alert(x);
outputs 55
Where as _
is a variable.
_ = + '5'
x = _ + 5
alert(x)
outputs 10
Additionally,
It would be interesting to know you could also achieve same thing with ~
(if string is int string (float will be round of to int))
y = ~~'5' // notice used two time ~
x = y + 5
alert(x);
also outputs 10
~
is bitwise NOT : Inverts the bits of its operand. I did twice for no change in magnitude.