Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does +"1" return an int?

Tags:

javascript

return "1";  // returns string
return +"1"; // returns int

I'd like to know what this method is called when using +"n" to convert from string to int.

like image 593
BenR Avatar asked Apr 30 '26 04:04

BenR


2 Answers

It's just the intrinsic type coercion that the unary + operator performs according to the language spec.

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).

So although conceptually it's just the opposite of unary -, since a + operation just means "multiply by positive 1" the only real work that's done is to coerce the value to a number.

like image 133
Pointy Avatar answered May 02 '26 17:05

Pointy


From MDN:

Unary plus (+)

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. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. 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.

Examples:

+3     // 3
+"3"   // 3
+true  // 1
+false // 0
+null  // 0
like image 35
Catalin MUNTEANU Avatar answered May 02 '26 17:05

Catalin MUNTEANU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!