How can you achieve module encapsulation in JavaScript?
Instruction: Explain different methods to achieve module encapsulation and provide examples.
Context: This question evaluates the candidate's ability to structure code in a modular fashion, using patterns or features like IIFEs, the Module pattern, or ES6 modules to encapsulate functionality.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Encapsulation exposes a deliberate interface while keeping implementation bindings local. A closure can hide state, and native ES modules provide module scope plus explicit imports/exports. Neither makes code delivered to the browser secret.
A factory closure creates independent instances; immediately calling such a function is the familiar IIFE module pattern:...