Skip to content

QuizNot attempted

require caches modules

What does main.js print?
// a.js
let x = 10;
module.exports = () => ++x;
// main.js
const f1 = require('./a');
const f2 = require('./a');
console.log(f1(), f2(), f1 === f2);
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 11 12 true
  • A module is evaluated once and cached by resolved path, so both require calls return the same function closing over the same x: f1() gives 11, f2() gives 12, and f1 === f2.
  • Not 11 11 false: that assumes two separate evaluations.
  • Not 11 11 true: same function means shared x, so the second call sees 11 and returns 12.
  • Not 10 10 true: ++x is pre-increment, it returns the new value.
  • This is how module-level singletons (DB pools, config) work
  • ESM caches the same way.