P.Ba
P.Ba

Reputation: 17

Problem with showing consecutive numbers after clicking the button

I have two files in which I wrote a simple number counter. The point is that when I click, I get an alert with each successive number plus one when I click the button. However, I have a certain problem. Well, here's a code for doing this:

```html
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <script src="index.js" defer></script>
</head>
<body>
    <button>Klik</button>
</body>
</html>
```
```js
let btn = document.querySelector('button');
let count = 0;
function test() {
    count++;
    alert(count);
}
btn.addEventListener('click', test);
```

And that code above works. Each time I click on the button, a new value appears, first 1 then 2 etc. However, this is no longer the case with this code:

```html
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <script src="index2.js" defer></script>
</head>
<body>
    <button>Klik</button>
</body>
</html>
```
```js
let btn = document.querySelector('button');
function test() {
    let count = 0;
    count++;
    alert(count);
}
btn.addEventListener('click', test);
```

In the case of this code, only one value appears (and this is every time when I click the button), and the only difference between one and the other code is that the variable count with the value 0 in the first code is in the global scope, and in the second in the functional scope. Can someone logically explain to me why the first code works, and the second one does not despite such minor differences?

Upvotes: 0

Views: 60

Answers (2)

Tom O.
Tom O.

Reputation: 5941

You need to change the scope of count so that it's declared outside of the event-handler function. The way you have it now, every time you click the button the count is reset to 0, which is not what you want. Try something like my example below which initializes the variable once to 0, then increments on each button click, like this:

let btn = document.querySelector('button');
let count = 0;

function incrementCount() {
  console.log(++count);
}

btn.addEventListener('click', incrementCount);
<button>Increment</button>

Upvotes: 1

R3FL3CT
R3FL3CT

Reputation: 586

This is because it's creating a new variable named count with a value of 0. It then increments this value, so it's equal to one. Every time the function is called, it creates a new count variable.

When you have it in the global scope, it's not creating a variable, it's just updating a global one.

Upvotes: 3

Related Questions