2

I have a very stupid problem. This code:

var x=5;
console.log(x*20+x-1);

prints out 104 as expected but this:

function Go(){
    x = document.getElementById("input").value;
    console.log(x);
    console.log(x*20+x-1);
}

prints out 5 and then 1004. Why is this?

console.log(x*20) prints 100. I tried putting brackets around it and then adding (x-1) but it still outputs 1004.

poke
  • 369,085
  • 72
  • 557
  • 602
Yordan Grigorov
  • 194
  • 1
  • 8

3 Answers3

3

The value property of the input element is a string, so your x is actually "5"—not the number 5. What follows is JavaScript’s way of doing implicit type conversion for arithmetics:

  "5" * 20 + "5" - 1
= 100      + "5" - 1
= "1005"         - 1
= 1004

So in the first step, "5" is correctly converted to the number 5, leaving 100 as the intermediary result. However, adding a string to a number will convert the number into a string, so what happens next is a string concatenation to "1005". Finally, the number 1 is subtracted from the string, which causes the string to be converted to a number again, yielding the final result: 1004.

To avoid this, you can simply convert the x to a number first:

var x = document.getElementById("input").value;
x = parseInt(x, 10); // or parseFloat(x) if you’re interested in a decimals
console.log(x * 20 + x - 1);

Fun fact: If you wrote x * 21 - 1, which is equivalent to your calculation, the problem wouldn’t have appeared.

poke
  • 369,085
  • 72
  • 557
  • 602
1

The value of an input element is a string value, so what you are getting is:

"5" * 20 = 100
100 + "5" = "1005"
"1005" - 1 = 1004

This has nothing to do with being in a function or not. Your two code snippets are not equivalent.

You can solve this by doing:

function Go(){
    x = +(document.getElementById("input").value);
    console.log(x);
    console.log(x*20+x-1);
}

That will convert the input element value to a numeric value at the beginning.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

document.getElementById("input").value returns a string. You need to convert it to and integer for it to work. So use parseInt()

function Go(){
    x = parseInt(document.getElementById("input").value);
    console.log(x);
    console.log(x*20+x-1);
}
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34