I read the following on a question on SO:
'7' + 4 gives '74', whereas '7' - 4 gives 3 in JavaScript
Why does this happen?
A Number String is a set of related math problems designed to teach strategies based on number relationships. It is a 10–15 minute routine that can be used during math instruction. Prepare an area to use the number string by gathering students in an area where the whole class meets.
The simplest way is to use a lib- but if you can't do that, use a string. Strings are almost infinite in length, therefore you can use them to store large "numbers". To subtract 2 numbers, you subtract each digit individually and carry over the borrows. This is the same case in programming.
+
is the String concatenation operator so when you do '7' + 4
you're coercing 4
into a string and appending it. There is no such ambiguity with the -
operator.
If you want to be unambiguous use parseInt()
or parseFloat()
:
parseInt('7', 10) + 4
Why specify the radix to 10? So '077'
isn't parsed as octal.
The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated: '7' + 4 => '7' + '4' => '74' But '-' is only defined for numbers, not strings, so the string '7' will be converted to number: '7' - 4 => 7 - 4 => 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With