Hi, I created a random maths generator and it works for everything except when it should be adding. What am I doing wrong?

See code below:

``````<body>
<div>
<h1>Let's do some randon maths! 🤪</h1>
<h3>
Select two numbers between 0-50 and then push the button below for some
random maths.
</h3>

<input type="number" id="value1" />
<p id="math">❓</p>
<input type="number" id="value2" />
<p id="total">=</p>
<button>Random maths!</button>
</div>
<script>
function randomMath() {
let a = document.getElementById("value1").value;
let b = document.getElementById("value2").value;
let math = Math.floor(Math.random() * 4);
let calculate;
let maths = document.getElementById("math").textContent;
let total = document.getElementById("total").textContent;

if (math === 0) {
calculate = a * b;
document.getElementById("math").innerHTML = "✖️";
document.getElementById("total").innerHTML = `= \${calculate}`;
} else if (math === 1) {
calculate = a / b;
document.getElementById("math").innerHTML = "➗";
document.getElementById("total").innerHTML = `= \${calculate}`;
} else if (math === 2) {
calculate = a + b;
document.getElementById("math").innerHTML = "➕";
document.getElementById("total").innerHTML = `= \${calculate}`;
} else if (math === 3) {
calculate = a - b;
document.getElementById("math").innerHTML = "➖";
document.getElementById("total").innerHTML = `= \${calculate}`;
}
}
let random = document.querySelector("button");
</script>
</body>
</html>
``````

Welcome there,

It sounds as though you are having an issue with JavaScript’s behind-the-scenes type conversion. You can read more about it here:
Type Conversions (javascript.info)

Try converting the input like this:

``````calculate = +a + +b;
``````

Or (probably better)

``````calculate = Number(a) + Number(b);
``````

Hope this helps

`+` is string concatenation. All html input values are strings. So you are concatenating strings.

The reason it works for the other calculations is due to JS’ type coercion: in those other branches of the `if` statement, `*`, `-` and `/` all expect numbers on both sides, so JS tries to be helpful and converts the string to a number rather than erroring (which would be preferable as it would have meant you would have been able to see what the issue was).

Edit: This is not great behaviour, in fact it’s extremely confusing, but it’s something useful that you’ll need to learn – if your input values are supposed to be numbers, make sure you convert them to actual numbers to avoid weird stuff happening.

Thank you both!

The calculator works.