What is the cleanest way to implement a JavaScript singleton pattern?

Totally agree with both of you guys — and just to add my two cents from experience working on modular applications, I’ve found that wrapping the javascript singleton inside a module pattern really pays off, especially when managing larger codebases with multiple files.

const Singleton = (() => {
  let instance;

  function init() {
    return { message: "I am the only instance!" };
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Usage:
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();

console.log(singleton1 === singleton2); // true

This approach essentially builds on the closure idea but ties it into the module pattern, making your javascript singleton even more modular and easy to integrate across multiple parts of your application. It’s my go-to when I’m aiming for organized, scalable code architecture.