Search code examples
javascriptstringnumbers

Why can I multiply a string in JavaScript, but not add it?


For my BMI calculator, I take user input from several input fields. I expect the value of imperialHeight to be 65 after the calculation, but it actually is 605.

// user input through input field with id imperialHeightFt = 5
// user input through input field with id imperialHeightIn = 5

let imperialHeight = (imperialHeightFt.value * 12) + imperialHeightIn.value;

Apparently, JavaScript does something like this:

5 * 12 = 60

'60' + '5' = '605'

After some research, I get that .value returns a string. It seems that JavaScript treats the string as a number anyway if I multiply it. This code returns 65, as expected.

let imperialHeight = (imperialHeightFt.value * 12) + (imperialHeightIn.value * 1);

My code works like this, but I'd like to know what happens here. Why can I use the string returned by .value to multiply, but not to add?


Solution

  • Because the + operator performs string concatenation when at least one operand is a string, whereas the * and other math operators attempt to convert each operand to a number.