JavaScript Performance Optimization Interview Questions and Answers

Prepare to measure JavaScript performance and choose optimizations that address real bottlenecks.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

The main thing to watch: avoid string concatenation with + inside a loop - each + creates a new string object, which can get expensive. Push parts into an array and call .join('') at the end instead. For everything else, modern engines optimize string operations well.

1. String Immutability: Since strings are immutable, any modification creates a new string, which can lead to memory overhead in loops or large data processing.

2. String Concatenation: Repeated string concatenation (using `+`) in loops can be inefficient due to the creation of many intermediate strings. Instead, consider using:

let str = ["Hello", "World"].join(" ");

3. Template Literals: While template literals improve readability, their performance is similar to regular string concatenation, but be mindful of excessive usage in performance-critical areas.

4. Avoiding Unnecessary String Operations: Frequent use of methods like replace(), slice(), or substring() on large strings can be costly due to the creation of new strings each time.

5. Memory Usage: If dealing with large datasets or strings (e.g., file contents), try to minimize unnecessary string operations to reduce memory consumption and processing time.

By keeping these in mind, you can avoid the most common string performance pitfalls in JavaScript.

Start with a representative workload and use browser performance tools or carefully placed Performance API measurements to identify where time is spent. Compare repeatable measurements before and after a change; avoid optimizing code based only on intuition or a single noisy run.

Measurement identifies the actual bottleneck and provides a baseline for judging whether a change helped. Optimizing based only on intuition can add complexity without improving user-visible performance.

Repeated reads and writes can cause extra style, layout, or paint work, especially when they force the browser to calculate layout synchronously. Grouping updates and avoiding unnecessary layout reads can reduce that work.

Smaller, correctly sized image resources take less time and bandwidth to download and decode. Responsive image selection can let the browser choose a suitable resource for the device and layout.

A classic script marked `defer` can download while HTML parsing continues, then execute after parsing and before `DOMContentLoaded`. It avoids blocking the parser while retaining document order among deferred classic scripts.

Unused code still costs bandwidth and may require parsing, compilation, or evaluation. Removing it can improve loading and responsiveness, especially on slower devices and networks.

Debouncing delays work until a burst of events has paused, which can reduce repeated expensive operations such as filtering after every keystroke. It is not appropriate when the interface must respond continuously during the event stream.

Throttling limits how often work runs during a continuing stream of events, while debouncing waits until the stream pauses. Throttling is often suitable for periodic scroll updates; debouncing is often suitable for settled search input.

Memoization can avoid recomputing results for repeated inputs by storing prior results, at the cost of memory and lookup overhead. It is useful when computation is expensive and the cache key correctly represents all relevant inputs.

Layout thrashing can occur when code alternates DOM writes with layout-dependent reads, forcing the browser to recalculate layout repeatedly. Batching reads and then writes can avoid many of these forced synchronous layouts.

A long task occupies the main thread, delaying input handling, rendering, and other queued work until it yields. Splitting work into smaller chunks or moving suitable computation off the main thread can improve responsiveness.

Core Web Vitals focus on loading performance, interactivity responsiveness, and visual stability through metrics such as LCP, INP, and CLS. They are field-oriented user experience measures, not a complete diagnosis of every performance issue.

Code splitting separates an application into chunks so the initial route can load only the code it needs and defer other features. Poorly chosen boundaries can add network round trips or delay code needed immediately, so measure the result.

Hints such as `preconnect` or `preload` can help the browser prepare for a known critical origin or fetch a resource needed soon. Incorrect or excessive hints compete for bandwidth and can make performance worse.

JavaScript Practical and Coding Interview Questions

Problem: Implement memoize for a deterministic function that receives JSON-serializable arguments. Repeated calls with the same arguments should reuse the cached result.

javascript

function memoize(operation) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = operation(...args);
    cache.set(key, result);
    return result;
  };
}

let calculations = 0;
const totalWithFee = memoize((amount) => {
  calculations += 1;
  return amount + 15;
});
console.log(totalWithFee(120), totalWithFee(120));
console.log('calculations:', calculations);