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

Building on @emma-crepeau idea — after working on larger projects, I realized sometimes structure helps readability as the codebase grows. In such cases, I’d prefer using ES6 classes combined with static properties. It feels more natural when working with a more object-oriented mindset while still sticking to the javascript singleton philosophy.

class Singleton {
  static instance;

  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    this.message = "I am the only instance!";
    Singleton.instance = this;
  }
}

// Usage:
const singleton1 = new Singleton();
const singleton2 = new Singleton();

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

Here, the javascript singleton benefits from the class syntax — it’s more readable for teams and scales nicely if your singleton needs to expand functionality over time. Plus, the constructor logic makes the behavior intuitive for anyone familiar with object-oriented programming.