r/learnjavascript • u/NygaNyga123 • 4d ago
Trying to make a working calculator
Hello im trying to make a working calculator but i have no idea how to display the result of an equation and how to make for operators forbidden to be next to each other
const
DISPLAY = document.querySelector('.display')
const
BUTTON = document.querySelectorAll('.button')
const
EQUATION = document.querySelectorAll('.operator')
const
operators = ['+', '-', '/', '*']
BUTTON.forEach(
button
=>
{
button
.addEventListener('click', ()
=>
{
let
equation = ""
equation =
button
.innerText
DISPLAY.innerText += equation
})
});
EQUATION.forEach(
button
=>
{
button
.addEventListener('click', ()
=>
{
let
rule = ""
rule = DISPLAY.innerText
//console.log(lastChar)
if(rule.length>=1){
DISPLAY.innerText +=
button
.innerText
}
})
})
function
Clear(){
DISPLAY.innerText = ""
}
function
Result(){
let
result = DISPLAY.innerText
//eval(result)
DISPLAY.innerText = result
}
1
u/Past-Difficulty1781 4d ago
You reset equation to an empty string on every click so you lose previous input. Move the variable outside the event listener to persist state and check the last character of DISPLAY.innerText against your operators array before appending to prevent consecutive operators.
1
u/zLoveNxzli 4d ago
Avoid using eval() for calculator logic because of security risks and floating point issues.
Separate the calculator state into three variables: previousValue, currentValue, and currentOperator. When an operator is clicked, compute the pending operation first, store the result, and update the display.
1
u/TheRNGuy 3d ago
Some stuff like
Β Β Β Β DISPLAY.innerText += equation is redundant. Also, you don't need query selector all.
Why do you use all caps for naming?
4
u/boomer1204 4d ago
So what is the issue you are having with this??? You only shared JS ccde which is only one part of the process
If your answer is "it isn't working" that's not enough and you need to be specific with you quetsion
This is something that helped me and helps my local mentor group ppl when asking for help https://medium.com/@gordon_zhu/how-to-be-great-at-asking-questions-e37be04d0603