1

I have a number of seconds in a string, like: '5'.

From that I need to get the number of milliseconds and it has to be of type Number, like: 5000.

I know that you can easily convert strings to numbers by prefixing them with a +

const result = +'5';

console.log(result, typeof(result));

However playing around I saw that that's not even necessary because JavaScript automatically does the conversion for you when you try to use arithmetic between strings and numbers.

const result = '5' * 3;

console.log(result, typeof(result));

console.log('5.3' * 3);

On the docs I only found info about the Number() constructor.

My question is: is it safe to use arithmetic on strings (except for the addition)? Can I rely on the behaviour showed above?

anotherOne
  • 1,513
  • 11
  • 20
  • 2
    Yes, anything other than `+` will automatically convert the operands to numbers. With that said, it's probably better to be explicit just in case. Helps when reading the code six months from now. Maybe you figure out you want to change that `a * 2 + b * 3` to a `a + b * 3` but you forgot that `a` was a string. – VLAZ May 17 '21 at 20:21

2 Answers2

2

Yes, it is safe. All arithmetic operations except a binary + will convert the operands to numbers. That includes bitwise operators as well as unary plus.

With that said, it is probably a good idea not to rely on this extensively. Imagine that you have this code:

function calculate(a, b) {
  return a * 2 + b * 3;
}

//elsewhere in the code
console.log(calculate("5", "2"));

This works fine because both a and b are multiplied, so are going to be converted to numbers. But in six months time you come back to the project and realise you want to modify the calculation, so you change the function:

function calculate(a, b) {
  return a + b * 3;
}

//elsewhere in the code
console.log(calculate("5", "2"));

...and suddenly the result is wrong.

It is therefore better if you explicitly convert the values to numbers if you want to do arithmetic. Saves the occasional accidental bug and it is more maintainable.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
2

Yes, but you have to be careful...

console.log('5.3' * 3);

console.log('5.3' + 3);

These two very similar functions cast the values different ways:

  • * can only be applied between two numbers, so '5.3' becomes 5.3
  • + can also concatenate strings, and the string comes first, so 3 becomes '3'

If you understand all these you can do this, but I'd recommend against it. It's very easy to miss and JS has a lot of weird unexpected casts.

Keith
  • 150,284
  • 78
  • 298
  • 434