I have a piece of code that counts. The function showResultAndCount()
shows counter
and adds 1, the other function showResult()
just shows counter
.
I would like both functions to be able to work with the latest value of the variable counter
. At the moment both functions seem to have their own version of the variable. How can I achieve this without using global variables?
This so elementary I assume it will be a duplicate, but I have no idea how this behaviour is called and therefore have no idea what I should be searching for on stack overflow or Google.
<script>
function showResultAndCount(counter) {
let someButton = document.getElementById('counter1');
someButton.addEventListener('click', function() {
counter++;
alert(counter);
});
return counter;
}
function showResult(counter) {
someButton = document.getElementById('counter2');
someButton.addEventListener('click', function() {
alert(counter);
});
}
</script>
<button id='counter1'>
Show counter and count
</button>
<br /><hr />
<button id='counter2'>
Show counter
</button>
<script>
let counter = '0';
counter = showResultAndCount(counter);
showResult(counter);
</script>