I have the following code
let chosenRating = 0;
for(button in ratingButtons){
ratingButtons[button].onclick = (e) => {
chosenRating = e.target.innerHTML;
ratingButtons.forEach(btn => {
btn.classList.remove('selected');
})
e.target.classList.add('selected');
}
}
I want to be able to access the chosenRating variable globally, but it just says it’s 0. I tried to just declare it and not assign it, but then it says it is undefined. When I console log inside the function, right after assigning it to e.target.innerHTML, I get the value that I want. But outside of the function, I don’t get the same output.
I thought that since I declared the variable globally, even if I don’t assign anything to it then and there, I’ll be able to access the variable globally. How can I fix this so that the innerHTML of the last button I click is stored as the value to the chosenRating variable?
2
Answers
Use
var
insteadlet
.let is a scope variable, so it can’t changed.
is ti something like that ?