I can't figure out how to update a global variable for a javascript calculator I am working on. I know using eval would make this a lot easier but from what I read online, eval from user input is not advised.
My idea is store the first number until an operation comes is clicked. Once that is clicked, store second number and then see what operation comes up by the user, where it is '=' or '+/*-' do the appropriate action. I have not completed the CE or AC or '.' buttons yet. There's no point in completely that if I can not update the global variable.
Within the function itself, I can change the variable firstNum and secondNum. From what I have read online, I believe I am not changing the global variable but the local instance of the variable.
I am hoping to be pointed in the right direction to get this done. I attempted to store in the number in an object and later reference that object when I needed to do an operation but I do not believe I did that quite right since I receiving a Reference Error.
Thank you in advance.
var theParent = document.querySelector("#container");
var display = document.querySelector("#display");
theParent.addEventListener("click", doSomething, false);
var reg = new RegExp('^\\d+$');
var result=0;
var symbol='';
var firstNum=0;
var secondNum=0;
function doSomething(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.innerHTML;
if (reg.test(clickedItem)) {
if (display.innerHTML==="0"){
display.innerHTML=clickedItem;
}
else {
display.innerHTML+=clickedItem;
}
}
}
if (clickedItem==='='){
console.log('check firstNum:' +firstNum);
console.log('check symbol:'+ symbol);
console.log('operations return: '+ operations(symbol));
result= operations(symbol);
console.log('result: '+ result);
display.innerHTML=result;
firstNum=result;
secondNum=0;
symbol='';
}
if (!(reg.test(clickedItem))&&symbol===' '&&clickedItem!=='=')
{
symbol=clickedItem;
display.innerHTML='0';
console.log('first op '+ symbol);
}
if (!(reg.test(clickedItem))&&symbol!==clickedItem&&clickedItem!=='=') {
solve(symbol);
symbol=clickedItem;
console.log('second op '+symbol);
}
if (symbol===''){
//firstNum = parseInt(display.innerHTML);
setFirstNum();
console.log("this firstNum in If: " +firstNum)
}
else if (reg.test(clickedItem)){
setSecondNum();
console.log("this secondNum in If: " +secondNum)
}
else {display.innerHTML='0';}
e.stopPropagation();
}
function setFirstNum(){
window.firstNum=parseInt(display.innerHTML);
}
function setSecondNum(){
window.secondNum=parseInt(display.innerHTML);
}
function operations(symbol){
var operation=[{
'+': firstNum + secondNum ,
'-': firstNum - secondNum ,
'÷': firstNum/secondNum ,
'X': firstNum*secondNum
}];
return operation[symbol];
}
function solve(symbol){
result=operations(symbol);
display.innerHTML=result;
firstNum=result;
secondNum=0;
}