I have this code snippet for creating a calculator:
const numbers = document.querySelector('.numbers')
const display = document.querySelector('.display')
const functions = document.querySelector('.functions')
const equalClear = document.querySelector('.equalClear')
numbers.addEventListener('click', e => {
// adding number to display
if(e.target.innerHTML == '1'){
display.innerHTML += '1';
}else if (e.target.innerHTML == '2'){
display.innerHTML += '2';
}else if (e.target.innerHTML == '3'){
display.innerHTML += '3';
}else if (e.target.innerHTML == '4'){
display.innerHTML += '4';
}else if (e.target.innerHTML == '5'){
display.innerHTML += '5';
}else if (e.target.innerHTML == '6'){
display.innerHTML += '6';
}else if (e.target.innerHTML == '7'){
display.innerHTML += '7';
}else if (e.target.innerHTML == '8'){
display.innerHTML += '8';
}else if (e.target.innerHTML == '9'){
display.innerHTML += '9';
}else if (e.target.innerHTML == '0'){
display.innerHTML += '0';
}
});
functions.addEventListener('click', e => {
// selecting a function and displaying it
if(e.target.innerHTML == 'Add'){
display.innerHTML += '+';
functionVal = add();
} else if(e.target.innerHTML == 'Subtract'){
display.innerHTML += '-';
functionVal = subtract();
} else if(e.target.innerHTML == 'Multiply'){
display.innerHTML += '*';
functionVal = multiply()
} else if(e.target.innerHTML == 'Divide'){
display.innerHTML += '/';
functionVal = divide();
}else{
display.innerHTML + 'Error'
}
numberVal = display.innerText;
console.log(numberVal, "numberVal");
console.log(functionVal, "functionVal");
});
equalClear.addEventListener('click', e => {
if(e.target.innerHTML === 'Clear'){
display.innerHTML = "";
}
else if(e.target.innerHTML = '='){
}
})
//calculator functions
function add(variable1, variable2) {
return variable1 + variable2;
};
function subtract(variable1, variable2) {
return variable1 - variable2;
}
function multiply(variable1, variable2) {
return variable1 * variable2;
};
function divide(variable1, variable2) {
return variable1 / variable2;
}
// operation in calculator
function operate(operator, num1, num2){
operate = operator, num1, num2;
}
operate(functionVal(numberVal,5))
console.log(operate, "this is an operation");
I am facing issues with calling "functionVal" and "numberVal" within the "operate" function. They are showing as undefined due to local scope. I attempted to give them global scope using "var" but had no success. Any suggestions on how to resolve this would be greatly appreciated.
Another concern is that when I try to log "functionVal" in "functions.AddEventListener," it displays NAN instead of the assigned function value. I expected it to show the actual function defined for "add" upon clicking the corresponding button. Any insights on what could be causing this discrepancy?
Thank you in advance for any assistance!
Best regards, A JavaScript beginner