I am attempting to create a simple addition calculator using javascript. My plan was to run a function when the button for one with the id “i” was clicked. This function would determine if there was a pre-existing value for “FirstNumberPicked”, and if not it would assign the number one to it. It would also asign the number one to “SecondNumberPicked”, if the reverse happened. Next I created a function that would add the two varrables together, when the answer button in HTML was pressed. Unfortunatly I learnt after reciving “undefined” as my result in the console that variable scope is a thing I then tried to fix it. (The HTML is not shared.)
Current Code in my IDE:
const i = document.querySelector("#i"); // The element with this ID is a button
const answer = document.querySelector("#answer")
let SecondNumberPicked;
let FirstNumberPicked;
i.onclick = onePick
answer.onclick = answerFunction
function answerFunction(params) {
console.log(FirstNumberPicked+SecondNumberPicked);
}
function onePick() {
if (FirstNumberPicked>0) {
let SecondNumberPicked = 1;
}else { let FirstNumberPicked = 1;}
}
I tried to to replace FirstNumberPicked with a variable within the function OnePick, that would then update the real FirstNumberPicked variable outside of the function and then use console.log() to find out if it would update it. I ended up getting the value of undefined for the FirstNumberPicked variable.