# 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;

function clickCounter() {
counter++;
console.log(counter);
}

• I don't think the task is actually possible as stated, suppose the page has an iframe, so far as I know there's no way to detect clicks inside the iframe. Certainly what you've written won't work in that instance. – Countingstuff Mar 26 at 0:47
• you are right! the question was very open and lacking of details tho – Pato Vargas Mar 26 at 6:02

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:

1. The counter variable is a global variable here which is not recommended
2. The function is not reusable. Suppose, I want to track clicks in 2 different sections in same document now, the approach will fail
3. Any user can easily modify counter value. Anytime in window, user can do counter = 0 and the value will reset to 0 losing data
4. What if user refreshes the pages? In that case, do we need to store the data or losing it would be fine
5. 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()

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()

})