JavaScript Under the Hood for Pythonistas (Summary)

Congratulations, you made it to the end of the course! The match log processor still returns the same scores for the Falcons and the Owls. Now you can also explain why it was slow, what kept a day of match records alive, and which parts of that story come from JavaScript and which from the engine. Your report for your Python teammate now rests on evidence.

One short run shows the processor’s final pieces: totals through an index, a record from the factory, a cleared history, a review note that doesn’t own its player, and the points question from your report:

Language: JavaScript
const teams = [
  { id: 1, name: "Falcons" },
  { id: 2, name: "Owls" },
];
const rows = [
  { team: 1, points: 3 },
  { team: 2, points: 2 },
  { team: 1, points: 4 },
];

function totalScores(teams, rows) {
  const names = new Map();
  for (const team of teams) {
    names.set(team.id, team.name);
  }
  const totals = new Map();
  for (const row of rows) {
    const name = names.get(row.team);
    if (name !== undefined) {
      totals.set(name, (totals.get(name) ?? 0) + row.points);
    }
  }
  return totals;
}

function matchRecord(id, team, points) {
  return { id, team, points };
}

const history = [matchRecord("M1", "Falcons", 3)];
const player = { id: "P1", team: "Falcons" };
const reviewNotes = new WeakMap();
reviewNotes.set(player, { checked: true });

console.log(totalScores(teams, rows));
history.length = 0;
console.log(history.length);
console.log(reviewNotes.get(player));
console.log([3, NaN, 4].includes(NaN));

Every line of output is fixed, so a test can check it:

Language: Program Output
Map(2) { 'Falcons' => 7, 'Owls' => 2 }
0
{ checked: true }
true

The 0 only means the history no longer refers to the match record. The record’s memory isn’t necessarily freed, and the program can’t tell when the collector reclaims it. The note comes back through the player, but the map doesn’t keep the player alive. The last true is the .includes(NaN) answer from your report.

In CPython, the same history lets go of its record at once, as a weak reference watching it shows:

Language: Python
import weakref

class Match:
    def __init__(self, match_id, team, points):
        self.id = match_id
        self.team = team
        self.points = points

history = [Match("M1", "Falcons", 3)]
ref = weakref.ref(history[0])
history.clear()
print(ref())

The weak reference is already dead:

Language: Program Output
None

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.