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.