-3

https://www.w3schools.com/code/tryit.asp?filename=FF1OPHNA043Z

I am playing around on w3school.com and while I can get operators such as (*),(/) to work, I can't get the addition or subtraction operators to work.

For example, in the link:

var x = document.getElementById("myNumber").value;
var y = x * 2
document.getElementById("demo").innerHTML = y;

will result in whatever x is times 2.
But when I try to use

+ or -

The result will be whatever x is plus 2. Or like below if x is 2.

22

Is x being treated as an Object?

Jay
  • 3
  • 1

2 Answers2

1

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.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

As stated in the comments, x is a String and thus the + operator adds the String 2 to your x String. Try parsing it into an integer to perform mathematical operations safely.

var x = parseInt(document.getElementById("myNumber").value, 10);
var y = x + 2
document.getElementById("demo").innerHTML = y;
larz
  • 5,724
  • 2
  • 11
  • 20