The Counter interview question is a fundamental JavaScript/TypeScript problem. You are asked to write a function that takes an integer and returns a "counter" function. This returned function, when called for the first time, should return . For every subsequent call, it should return the previous value plus one (, then , and so on).
Tech giants like Google and Meta use the Counter coding problem to test a candidate's understanding of Closures. Closure is a core concept in functional programming where an inner function has access to the variables of its outer function even after the outer function has finished execution. This problem is a quick way to verify if a candidate knows how to maintain state without global variables.
This problem uses the Closure pattern.
Initialize createCounter(10).
Closures are the backbone of many design patterns in JavaScript (like the Module pattern). Be prepared to explain exactly where the state is being stored in memory.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Binary Tree Preorder Traversal | Easy | Solve | |
| Array Partition | Easy | Solve | |
| Customer Who Visited but Did Not Make Any Transactions | Easy | Solve | |
| Remove Linked List Elements | Easy | Solve | |
| Running Sum of 1d Array | Easy | Solve |