CodeBlanks Logo Icon CodeBlanks

Garbage collection

Learn V8 garbage collection and generational GC.

Garbage collection

V8 uses generational garbage collection. New objects start in the young generation; those that survive a few GC cycles are promoted to the old generation. The young generation is collected often and fast; the old generation is collected less often and more thoroughly.

We can model which generation an object belongs to by its age: gcGeneration(ageMs). Objects past the PROMOTION_AGE threshold count as 'old', the rest as 'young'. Example: gcGeneration(100) returns 'young', gcGeneration(5000) returns 'old'. This explains V8's promotion logic with a simple rule. Real V8 generations are more complex (Scavenger, mark-sweep) but the core idea stands.

The promotion threshold

In this lesson we write the gcGeneration function. We define the PROMOTION_AGE constant and check whether the age crosses it with the ternary operator. If it does we return 'old', otherwise 'young'.

Example: const PROMOTION_AGE = 2000; function gcGeneration(ageMs) { return ageMs >= PROMOTION_AGE ? 'old' : 'young'; }. gcGeneration(100) returns 'young', gcGeneration(5000) returns 'old'. The ternary has the form condition ? true : false; it is shorthand for if/else. This model ties V8's generation promotion to age and yields deterministic output.

Practice Write the GC generation function

Define const PROMOTION_AGE = 2000. Write function gcGeneration(ageMs) { return ageMs >= PROMOTION_AGE ? 'old' : 'young'; }. Print console.log(gcGeneration(100)) and console.log(gcGeneration(5000)).

Starter code

index.js
// Define a promotion threshold constant
// Write gcGeneration: 'old' if age exceeds threshold, else 'young'
// Print two calls (100 and 5000)
// write here

Sample solution

index.js
const PROMOTION_AGE = 2000;
function gcGeneration(ageMs) {
  return ageMs >= PROMOTION_AGE ? 'old' : 'young';
}
console.log(gcGeneration(100));
console.log(gcGeneration(5000));

Expected output

young
old

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is an object promoted from young to old?

  • After surviving several GC cycles Correct answer
  • Hemen
  • Asla
  • Sadece hata durumunda

Explanation: Surviving objects are promoted to the old generation.

2 Complete the ternary expression

Question
return ageMs >= PROMOTION_AGE ? '____' : 'young';
Answer
return ageMs >= PROMOTION_AGE ? 'old' : 'young';

Explanation: Past the threshold it returns 'old'.

3 Match each concept to its description

Term Meaning
Young generation New objects
Old generation Surviving objects
PROMOTION_AGE Promotion threshold
Ternary Conditional expression

All lessons in Expert