CS Fundamentals Trainer · JavaScript · Performance & Memory

In V8, can the large array big be garbage-collected while keep is still alive?

In V8, can the large array `big` be garbage-collected while `keep` is still alive?

function setup() {
  const big = new Array(1e6).fill('x');
  const logSize = () => console.log(big.length);
  logSize();
  return () => 'small';
}
const keep = setup();
  1. Yes, because the returned function doesn't mention `big`, and V8 tracks captured variables separately for each closure.
  2. No, because closures created in the same scope share one context object, and `logSize` put `big` into it.
  3. No, because a function keeps its local variables alive for as long as its source code is loaded.
  4. Yes, but it happens later, once `setup` runs a second time and V8 replaces the old context.

Difficulty: hard

Answer this question

Related questions