Interviewer: You have 5 years of experience and still can’t answer this simple question?
A Fundamental Concept Even Experienced Developers Can Overlook
During a recent mock interview with a candidate having five years of experience, I posed a question I often find revealing: “What was the biggest technical embarrassment you’ve faced in an interview?”
His answer immediately highlighted a common misunderstanding in web/node development.
He recounted a recent experience during the second technical round at Zepto. The interviewer presented him with a seemingly simple scenario:
The scenario:
One Module file util.js in which just console.log('util')was added.
Two JavaScript Files: Both files import util.js.
Question was: How many times will ‘util’ be printed to the console?”
//util.js
console.log('utill');
// A.js
import './util.js';
// B.js
import './util.js';He said, he was damn sure that util was printed twice, he told me that as soon as he said that twice, the interviewer made a cunning smile and said Let’s move to the next question. and after that he just asked one question and wrapped the interview.
This scenario is a brilliant test of a developer’s understanding of module caching, a fundamental concept often overlooked until it produces an unexpected outcome. While it might seem intuitive that util would print twice, the reality is different.
The Module Caching Mechanism
When js engines/bundlers first encounters a require() or import statement for a module (like util.js), it performs the following steps:
- Loads and Executes: The module’s code is loaded and executed. Any top-level code, such as
console.log('util');, runs at this stage. - Caches the Export: The module’s
exportsobject is then stored in the internal module cache. This cache is a global object, unique to the running process. - Returns from Cache: For all subsequent
require()orimportcalls for the same module path within that process, Node.js doesn't reload or re-execute the module. Instead, it simply returns the cachedexportsobject.
Therefore, regardless of how many times util.js is imported by different files within the same Node.js process, the console.log('util'); statement within util.js will execute only once – the very first time the module is required.
Tags for SEO
#reactjs #frontend #javascript #html
