Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
Singleton
easy15 min
Implement a class whose constructor and static access method always return the same shared instance within its module.
Requirements
Export a class named Singleton with a public constructor and a static getInstance() method. Both new Singleton() and Singleton.getInstance() must return the same object.
Expose a writable numeric value property, initialized to 0 only when the first instance is created. Later constructor calls must preserve any changes to it.
The shared object must be an instance of Singleton. Keep cached state inside the module or class; do not attach it to globalThis or other global objects.
The singleton lifetime is one loaded module in one JavaScript runtime. Persistence across reloads, multiple browser tabs, workers, and subclasses is outside scope. No reset API is required.
Examples
Example 1
Input: const a = new Singleton();
const b = Singleton.getInstance();
a === b;
Output: true
Example 2
Input: const a = Singleton.getInstance();
a.value = 7;
new Singleton().value;
Output: 7
Provide one shared class instance per loaded module.
What the tests check
Initializes shared state to zero
Returns one identity across repeated constructor calls