Counting the number of click on the entire page In an interview I was giving the following problem:


  Count the number of click on on the entire page.


Can you think of a better way to do this?

let counter = 0;
document.addEventListener('click', clickCounter);

function clickCounter() {
  counter++;
  console.log(counter);
}
From my experience, this is a good first cut solution for a less experienced candidate as opposed to some experienced candidate. Also, a lot of other info is missing in question such as was there any further discussion on how to improve the solution or about adapting some good practices or how to make this code bug free etc.

I will try to list down possible issues which can to addressed:


The counter variable is a global variable here which is not recommended
The function is not reusable. Suppose, I want to track clicks in 2 different sections in same document now, the approach will fail
Any user can easily modify counter value. Anytime in window, user can do counter = 0 and the value will reset to 0 losing data
What if user refreshes the pages? In that case, do we need to store the data or losing it would be fine
If some additional functionality needs to be added (send total counter to backend server etc), so how easily it can be added without modifying the existing code


A lot of things depends on how the discussion goes after you present the solution. You can use closures, class based approach etc. I will try to list them below.

1. Use closure

(Not the best approach but better than OP's)    



const clickCounter = clicker()
document.addEventListener('click', clickCounter);

function clicker() {
  let counter = 0
  return function() {
    ++counter
    console.log(counter)
    return counter
  }
}




2. Use class like approach


This is the one people generally expect and works best; covering most of the cases  
You can also do the same by using ES6 classes    
Adding new functionality is lot more easier here




function Counter() {
  let clicks = 0
  this.registerClick = function() {
    ++clicks
    console.log(clicks)
    return clicks
  }
}

const clicker = new Counter()

document.addEventListener("click", function() {
  clicker.registerClick()
})




Hope it helps. Revert for any doubts.