When creating a calculator generally using a switch statement works for adding,subtracting etc, in this scenario I am not sure where the Switch statement would go or if its needed, so that the calculator can do its mathematics?
const screen = document.getElementById('screen');
const btn = document.querySelectorAll('.btn');
for (const btns of btn) {
//press button by index
btns.addEventListener("click", (num) => {
const numValue = num.target.innerText;
const textNode = document.createTextNode(numValue);
if(numValue === "="){
}
screen.appendChild(textNode)
});
}
switch(numValue){
case "+":
num + num
break;
case "-":
num - num
break;
case "/":
num / num
break;
case "*":
num * num
break;
case "*":
num - num
break;
default:
console.log("Error")
}
<div id="screen"></div>
<div>
<button class="btn">+</button>
2
Answers
In order to perform mathematics when the "=" button is pressed in a calculator, you need to keep track of the numbers and the operation to perform like this.
I have two variables currentNumber and operation that keep track of the current number and the operation to be performed.
When a calculator button is clicked, we check if it is a number or an operation symbol.
If it’s a number, we concatenate it to the currentNumber variable.
If it’s an operation symbol, we store it in the operation variable.
When the "=" button is pressed, we call the calculate function passing the current number, the number on the screen, and the operation.
The calculate function uses a switch statement to perform the correct operation based on the operation variable.
You can try the following way: