Reputation: 4433
I have seen code where strings were casted to numbers using the plus operator.
This would look something like:
var x ="5",y;
y = +x;
console.log(typeof y) //number
How does this work?
Upvotes: 2
Views: 64
Reputation: 12042
var x = "5",
y;
You're declaring two variables named respectively x
and y
. The former is set to hold the string "5"
, the latter holds the undefined
value(since it's declared but not defined).
Then you're setting y
to be the conversion in Number
type of the string "5"
(via the unary operator +
), which is 5
. So you're getting typeof y
to be number
.
The +
operator is the unary operator. It evaluates an object trying to convert it into a number.
Upvotes: 0
Reputation: 382122
In fact, there are two +
operators : the binary + operator and this one : the Unary + operator.
See how it's described in the 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. For example, y = +x takes the value of x and assigns that to y; that is, if x were 3, y would get the value 3 and x would retain the value 3; but if x were the string "3", y would also get the value 3. 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.
Upvotes: 3