Reputation: 197
The following expressions give peculiar result in JavaScript.
typeof (5 + "7") // Gives string
typeof (5 - "7") // Gives number
How do I get the result of the first expression as a number type?
Is there any way to do that without explicitly converting 7 to a number?
Please clarify.
Upvotes: 1
Views: 57
Reputation: 23816
Try this way parsing string to integer first. You can parse string implicitly with +
or parse to integer with parseInt
.
typeof (5 + +"7")
or
typeof (5 + parseInt("7"))
Upvotes: 4
Reputation: 700362
Yes, there is a way to do that without explicitly converting the string to a number, and that is by implicitly converting the string. You can for example use the +
operator, which will cause an implicit conversion of the string to a number, as it can only be applied to a number:
typeof (5 + +"7")
That's not very readable code, though. You are better off with an explicit conversion:
typeof (5 + parseFloat("7"))
Upvotes: 1
Reputation: 318212
The plus sign in javascript adds numbers together, but it also concatenates strings, and when one of the values being added together is a string, the latter is done, regardless of what the other values are.
The minus sign subtracts, and you can't subtract a string from a string, so it's only meaning is to subtract numbers
So in other words
5 + "7" === "57" // string
5 + 7 === 12 // number
5 - "7" === -2 // number
so no, you'd have to convert the string to a number to be able to add it to another number
5 - ( parseInt("7", 10) ) === -2 // number
5 - ( +"7" ) === -2 // number
Upvotes: 0
Reputation: 7490
The only way you'd be able to so that is by converting the string to a number
typeof (5 + parseInt("7"))
N.b. that's if you are using the plus operator, multiply/divide/minus work differently and will convert the string type to a number (unless NaN)
Upvotes: 0