JavaScript Postfix vs. Prefix
Interesting part of JavaScript 👻
Recently, I started solving some interview questions, and one of the questions was to create a counter with several actions. Here is the task description.
Implement a function makeCounter that accepts an optional integer value
(defaults to 0) and returns an object that contains the following methods:
get(): returns the current value.
increment(): increments the current value and returns it.
decrement(): decrements the current value and returns it.
reset(): resets the current value to the initial value.At the first glance, I was like…okay, this sould be easy for me to solve, but I did not pass the task.
This was my approach:
interface Counter {
get: () => number;
increment: () => number;
decrement: () => number;
reset: () => number;
}
function makeCounter(initialValue: number = 0):Counter {
return {
get: () => initialValue,
increment: () => initialValue++,
decrement: () => initialValue--,
reset: () => initialValue,
}
}
const counter = makeCounter(1);
console.log(counter.get())
console.log(counter.increment())
console.log(counter.increment())
console.log(counter.reset())Can you guess the result?
Get Shan’s stories in your inbox
Join Medium for free to get updates from this writer.
The result is 1, 1, 2, 3 , I thought it should be 1, 2, 3, 1 , but why?
Blind spots
- The
makeCounterfunction accepts a parameter with a default value of 0. In my approach, I used the parameter directly, which caused some bugs. I should have created another variable and assigned the value ofinitialValueto it to help keep track of the state. - The
initialValue++is a postfix increment operator, which returns the value before incrementing. Therefore, when I executedcounter.increment()to be 2, it had the previous value ofinitialValue, which was 1, and so on. Check the diagram below for more clarity.
Solution
- Create a variable to keep track of the latest state.
- Use prefix increment operator to make sure getting the updated result.
interface Counter {
get: () => number;
increment: () => number;
decrement: () => number;
reset: () => number;
}
function makeCounter(initialValue: number = 0):Counter {
let value = initialValue;
return {
get: () => value,
increment: () => ++value,
decrement: () => ++value,
reset: () => ( value = initialValue),
}
}
const counter = makeCounter(1);
console.log(counter.get())
console.log(counter.increment())
console.log(counter.increment())
console.log(counter.reset())Here is the diagram.










