---
title: "Singleton Pattern in JavaScript"
description: "What is Singleton Pattern? The singleton pattern is a design pattern that restricts the instantiation of a class to one."
url: "https://h3manth.com/scribe/singleton-pattern-javascript/"
canonical_url: "https://h3manth.com/scribe/singleton-pattern-javascript/"
markdown_url: "https://h3manth.com/scribe/blog/singleton-pattern-javascript.md"
publishDate: "2012-07-10T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript"]
word_count: 178
reading_time_minutes: 1
x_markdown_tokens: 410
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Singleton Pattern in JavaScript

> What is Singleton Pattern? The singleton pattern is a design pattern that restricts the instantiation of a class to one.

**What is Singleton Pattern?**

The singleton pattern is a design pattern that restricts the instantiation of a class to one object, much inspired from singleton set {0}.

**Where is it useful?**

  * Controlling concurrent access to a shared resource.

  * Abstract Factory implementation.

  * One time read variables. etc

**What is the use of it?**

Well despite the arguments and down votes for Singleton Pattern, it's still surviving! And in JS it's useful for :

  * Encapsulation of members & functions.

  * Creating Namespace.

  * Encourages code reuse.

  * Logically organisation of code gets easier.

**Singleton implementation with JavaScript :**

function SalarySingleton() {

if (typeof Singleton.salary === 'object') {
    
    
    return Singleton.salary;
    

}

this.setSalary = function(amt) {
    
    
    this.amt = amt;
    

} this.getSalary = function() {
    
    
    return this.amt;
    

}

Singleton.salary = this;

}

var emp1 = new SalarySingleton(); emp1.setSalary(60000); 

Do express your <3 towards singleton pattern!

**EDIT 0 :** iife to avoid new.

var singleton = (function () {
    
    
    var amt; 
    return { 
        getSalary: function () { return amt; }, 
        setSalary: function (amount) { amt = amount; }}; 
    }
    

());
