1

I recently wrote some code that is grabbing text from two separate elements and then subtracting them, to my surprise I didnt have to convert them first to integers. I did a little looking around and it seems JavaScript converts strings to numbers when using the subtraction operator. Does anyone know if this is ok to leave them as strings or for best practice should they first me converted to integers? and if so why? Thank you.

example: "10" - "6" = 4

wallrouse
  • 116
  • 1
  • 13
  • First of all, there is no such thing as an integer type in javascript, only doubles that can be rounded down to integers. I would not convert them first, just subtract the strings (unless you want to round down or up to nearest integer, or make sure it is an integer or something). I would definitely leave comments explaining that it gets converted though. – Mattias May 10 '18 at 22:42
  • 1
    Or parse to be explicit in your logic. This is a very opinion based question. – Taplar May 10 '18 at 22:43
  • Whoa... That's interesting. Even still, I would definitely use `parseInt` to convert them first. – spencer.sm May 10 '18 at 22:45
  • `Does anyone know if this is ok to leave them as strings or for best practice should they first me converted to integers?` yeah leave it. That is, if you hate yourself. Let's say that in half a year you go back to change something in that code. You see `a - b` and you change that to `1 + a - b`. Since both variables were actually strings, yet, you forgot, you now get `104` as a result. You don't notice because it's such a small fix. Alternatively, you have some memory that some variables somewhere were actually strings - instead of adding 2 bytes of code, you spend 5 minutes tracking that. – VLAZ May 10 '18 at 23:44

1 Answers1

4

[…] to my surprise I didnt have to convert them first to integers […]

A couple more surprises, then:

So, your string values were coerced to floating-point values, in the context of the arithmetic operation. JavaScript didn't tell you this was happening.

This is a source of bugs that can remain hidden for a long time, because if your string values would successfully convert to a number, the operation would succeed, even if you would expect those values to raise an error.

js> "1e15" - "0x45"  // The reader might have expected this to raise an error.
999999999999931

The brief “Wat” presentation by Gary Bernhardt is packed with other surprising (and hilarous) results of JavaScript's implicit type coercion.

Does anyone know if this is ok to leave them as strings or for best practice should they first me converted to [numbers]?

Yes, in my opinion you should do arithmetic only on explicitly-converted numbers, because (as you discovered) for newcomers reading the code, the implicit coercion rules are not always obvious.

bignose
  • 30,281
  • 14
  • 77
  • 110