What does = +_ mean in JavaScript

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, and null.
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 to NaN.

It is also noted that

unary plus is the fastest and preferred way of converting something into a number

Leave a Comment