DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

8

JavaScript Design Patterns - Creational - Singleton

Singleton pattern limits the number of instances of a particular object to just one while providing a global access point to this instance.

Singletons reduce the need for global variables, which avoids the risk of name collisions.

In the example below, we check in the constructor() { ... } if an Animal instance exists or if we need to create a new one.

class Animal {
  name;

  constructor() {
    if (typeof Animal.instance === 'object') {
      return Animal.instance;
    }

    Animal.instance = this;

    return this;
  }
}

export default Animal;
Enter fullscreen mode Exit fullscreen mode

You can see that code in action on Stackblitz here: https://stackblitz.com/edit/vitejs-vite-an7es6?file=main.js


I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Warp.dev image

Warp is the #1 coding agent.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Join the Algolia MCP Server Challenge: $3,000 in Prizes!

Explore the intersection of AI and search technology by building with the Algoliaโ€™s MCP Server. Three talented winners will be selected to share in our $3,000 prize pool!

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. โค๏ธ