In calculator we use:
const input = document.getElementById("display");
Here display is the input element where the calculator values are shown.
1. Why do we use String for user input?
When the user clicks number buttons we need to join the digits together.
For example:
currentValue += value;
If the user clicks:
5 → 0
We need:
"5" + "0" = "50"
So, we keep the entered value as a String.
This makes it easy to enter multiple digits like:
5 → 0 → 2
Result:
"502"
2. Why do we convert String to Number?
When we perform a calculation JavaScript must treat the values as numbers.
For example:
"50" + "2"
Since both are Strings JavaScript joins them together:
"502"
But we actually want:
50 + 2 = 52
Therefore before calculation we convert the String into a Number:
const leftOperand = Number(previousValue);
const rightOperand = Number(currentValue);
Now:
Number("50") → 50
Number("2") → 2
So JavaScript can perform the actual mathematical calculation:
50 + 2 = 52
**
- Why do we convert Number back to String? **
After calculation the result is a Number.
For example:
currentValue = leftOperand + rightOperand;
The result is:
52
This is a Number.
We convert it back to String using:
currentValue = currentValue.toString();
Now:
52 → "52"
We do this because our currentValue is used again for handling the calculator's displayed/input value.
Simple Flow
We use String while entering digits convert String to Number when performing calculations and convert the result back to String so it can continue to be handled as the calculator's input/display value.

Top comments (0)