JS Built-ins
Modulesintermediate

Singleton Module

A singleton module ensures only one instance exists. ES modules are singletons by nature β€” re-importing the same module returns the cached instance. Simulate with a closure that tracks whether an instance was created.

πŸ’‘ Hints (5)
  • β€’ Use a closure to maintain instance and nextId state
  • β€’ Check if instance already exists
  • β€’ Only create a new instance if it does not exist
  • β€’ Assign the id from nextId and increment nextId
  • β€’ Return the same instance on subsequent calls