3 JavaScript questions to watch out for during coding interviews
Daniel Borowski
1.5K29

Thanks for these good examples of JS interview questions. I like how you emphasized understanding JS fundamentals.

Regarding Question #2 (looping), just using let and const would make the code more readable and safe.

Regarding Question #3 (debouncing), while it’s a useful exercise to make a debouncer and it’s only a few lines of code, I’d recommend just using a micro-library for it, to reduce testing surface area and save time.

Also, the example debouncer you shared is making unnecessary calls to the timers API. Instead, it can spare the task queue by just calculating whether to call fn. Here’s an alternative:

const EPOCH_START_DATE = new Date(0)
const debounce = (fn, delay) => {
let lastCallDate = EPOCH_START_DATE
return (...args) => {
let curDate = new Date()
const shouldSkip = new Date() - lastCallDate < delay
if (shouldSkip) {
return
}
lastCallDate = curDate
return fn.apply(null, args)
}
}

To summarize the differences:

  • This version calls fn immediately the first time it is called.
  • This version is synchronous and uses return values. The inner function returns undefined when the function is called before delay milliseconds have elapsed since the last call to fn. Otherwise, it returns the result of calling fn with the latest arguments.
  • This version doesn’t bother with context, because using this is (in my opinion) to be avoided, and the caller can always bind fn if necessary.
  • And minor style differences to better-communicate programmer intent.