skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. I think you get your data through <input> element, and by default, the value attribute (what the user writes) is always string.

    And in JavaScript, multiplying and adding strings will always result in a string therefore use Number() to convert your data to numbers.

    let imperialHeightFt = document.getElementById("imperialHeightFt");
    let imperialHeightIn = document.getElementById("imperialHeightIn");
    
    let imperialHeight = Number(imperialHeightFt.value) * 12 + Number(imperialHeightIn.value);
    console.log(imperialHeight);
    <input id="imperialHeightFt" value="5" />
    <input id="imperialHeightIn" value="5" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search