DEV Community


Discussion on: Singleton Pattern in Javascript

belkheir profile image
Mahamed Belkheir

Honestly, Singleton is that one pattern that doesn't make much sense to use in a language like Javascript where you can create one-off object instances without a class and define functionality for it.

The Singleton's getInstance pattern is more useful in languages like Java where managing when an instance is created and used is a bit more painful, but in js you can easily make sure a single instance is created by declaring it on the package scope, any further imports do not re-run the file, and it just uses the same instance.

andi23rosca profile image
Andi Rosca • Edited

I agree. Singletons are less of a design pattern and more of a work-around for the limitation of languages that only let you use classes and nothing else.

And apart from some sense of "this must be readable because I'm using design patterns" I think most people will find

// Singleton.js
export const Singleton = { name: "John" };
// some other file
import { Singleton } from "...";
Enter fullscreen mode Exit fullscreen mode

way more readable than the 2 different files presented in the example, with so much ceremony around what you are actually trying to accomplish.

bibekkakati profile image
Bibek Author

Hey Mahamed Belkheir, you are right we can create one-off object instance directly. I prefer to follow the common implementation way of these design patterns. It also helps to understand the code better if someone is coming from other language. At last, in javascript we have two choices, modularisation approach or singleton approach.

Forem Open with the Forem app