← All lessons
JavaScript: Interaction
Variables and a counter
Your goal: Remember a number between clicks.
Learn
A variable stores a value. let allows the value to change. Each click increases count and updates the text.
View starter code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My hobby page</title>
<style></style>
</head>
<body>
<h1>Practice counter</h1>
<p id="count">0</p>
<button id="add">Add a session</button>
<script>
let count = 0;
document.getElementById("add").addEventListener("click", function () {
count = count + 1;
document.getElementById("count").textContent = count;
});
</script>
</body>
</html>Your challenge
Add a second button that resets the counter to zero.
Keep developing your hobby page: Download HTML before leaving the sandbox, then choose Open HTML file when returning to your project. Load saved draft restores only this lesson’s draft in this browser.
Practise in the sandboxShow a hint
Give the new button id="reset" and set both count and the displayed text to 0 in its click handler.
Show a sample answer
Try the challenge first. This is one possible answer or a snippet to adapt.
<button id="reset">Reset</button>
// Add inside the script:
document.getElementById("reset").addEventListener("click", function () {
count = 0;
document.getElementById("count").textContent = count;
});Check your work
Three clicks show 3; Reset shows 0; another click shows 1.
Completion is your own check, not an automatic grade.