Nope, x
is a string.
var input = document.querySelector('input');
var value = input.value;
console.log(value, typeof value);
<input type="text" value="2" />
Since +
is also used for string concatenation, the designer of JS decided that in this case, it would treat any actual numbers like strings and concatenate them.
var input = document.querySelector('input');
var value = input.value + 2; // Basically turns in to "2" + "2"
console.log(value, typeof value);
<input type="text" value="2" />
This, however, doesn't apply to -
:
var input = document.querySelector('input');
var value = input.value - 2; // Equivalent to 2 - 2 === 0
console.log(value, typeof value);
<input type="text" value="2" />
So what you need to do is convert the string to a number. My personal favorite is using the Number
function:
var input = document.querySelector('input');
var value = Number(input.value) + 2;
console.log(value, typeof value);
<input type="text" value="2" />
You also could use parseFloat
, which is functionally equivalent to Number
, or parseInt
if you want a non-floating point value and/or want to specify the base.