Skip to main content

Command Palette

Search for a command to run...

JavaScript Design Patterns — Creational — Singleton

Published
1 min read
N

I'm Nhan. I'm a web developer from Vietnam. I have over 5 years of experience in the Angular framework.

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;

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:

More from this blog

Nhan Nguyen's blog

88 posts

I’m a web developer, and I am really passionate about learning web development.