How to reset a number after reaching a value?

The number increases by 1 after each click, I need it to be reset back to zero when it reaches 3. Any hints? Edit fiddle - JSFiddle - Code Playground

document.querySelector('button').addEventListener('click', () => {
let n = document.querySelector('.cscore').innerHTML
if (n === 3) {
n = 0
document.querySelector('.cscore').innerHTML = n

What is the data type that n is being set to? Hint: It is not a number.

Since n is not a number this will never be true.

1 Like

Thank you. Is it weird that I have to reset it to -1 for it to be reset to 0 after reaching 3? Also, should I ideally reset it to a number or to a string?

Code goes line by line. What follows your if statement?

An increment to n?

Yup. You reset and immediately increase it.

1 Like

I’m going off on a bit of a tangent here, but I would suggest you be wary of holding your app state inside the DOM (right now the n value depends entirely on some element’s innerHtml). If instead you maintain your state in JavaScript, and update the DOM based on the state, then you won’t need to worry so much about converting between data types and so on.

For example:

let score = 0;

document.querySelector("button").addEventListener("click", () => {

function incrementScore() {
  if (score === 3) {
    score = 0;

function renderScore() {
  document.querySelector(".cscore").textContent = score;

This is just one way to do it, the sky’s the limit of course.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.