Question Bank
JavaScript Modules and Encapsulation Quiz
Difficulty: Medium
Compare the module patterns that ship in modern JavaScript: ES modules, the revealing-module IIFE, classic singletons, and method-borrowing via `call`, `apply`, and `bind`.
JavaScript Modules and Encapsulation Quiz
Compare the module patterns that ship in modern JavaScript: ES modules, the revealing-module IIFE, classic singletons, and method-borrowing via `call`, `apply`, and `bind`.
1,187 views
15
Implement a small ES module mathUtils.js that exports two pure functions, add and subtract. Show how to consume them with named imports.
Examples
Example 1:
Input: import { add } from './mathUtils.js'; add(2, 3)
Output: 5
Explanation: Named exports surface the functions on the module record; the importer pulls them in by name.List three ways to evaluate circleMath.area(4) with different pi values: implicit this, explicit call/apply, and pre-bound via bind. Output the four results.
Examples
Example 1:
Input: circleMath.area(4), circleMath.area.call({ pi: 3.14159 }, 4), circleMath.area.apply({ pi: 3.14159 }, [4]), circleMath.area.bind({ pi: 3.14159265359 })(4)
Output: 50.24, 50.26544, 50.26544, 50.26548245744
Explanation: `call` invokes immediately with positional args, `apply` invokes immediately with an args array, `bind` returns a new function with `this` pre-set.Rewrite the student object as a revealing-module IIFE so only the render method is exposed. Reads of student.getName and student.data should fail.
Examples
Example 1:
Input: studentModule.render(); studentModule.getName; studentModule._data
Output: [3], undefined, undefined
Explanation: Only `render` lives on the returned object; `_name`, `_data`, and `_getName` are captured by the IIFE's closure and unreachable from outside.Implement a Singleton using an IIFE and closures so that every call to getCount() returns the same instance, with a shared counter state.
Examples
Example 1:
Input: const a = obj.getCount(); const b = obj.getCount(); a.add(); a.add(); console.log(a.count, b.count)
Output: 2 2
Explanation: `a` and `b` reference the same instance because the factory caches it in the closure.Name the practical differences between an ES module and an IIFE-based module. Cover scope, evaluation timing, and tooling.
Examples
Example 1:
Input: compare `import { x } from './m.js'` versus `(function () { const x = 1; return { x }; })()`
Output: ES modules are deferred, strict, tree-shakeable, and produce live bindings; IIFEs run immediately and produce snapshots.
Explanation: Both encapsulate, but ES modules give the bundler enough static information to remove unused exports.