---
title: "Singleton function in JavaScript"
description:
  "Creating a singleton function in JavaScript could be tricky. This blog
  discusses how to do it and when it should be done."
canonical_url: "https://www.bigbinary.com/blog/singleton-function-in-javascript"
markdown_url: "https://www.bigbinary.com/blog/singleton-function-in-javascript.md"
---

# Singleton function in JavaScript

Creating a singleton function in JavaScript could be tricky. This blog discusses
how to do it and when it should be done.

- Author: Neeraj Singh
- Published: April 11, 2010
- Categories: JavaScript

Recently I was discussed with a friend how to create a singleton function in
JavaScript. I am putting the same information here in case it might help someone
understand JavaScript better.

## Creating an Object

Simplest solution is creating an instance of the object.

```javascript
var Logger = function (path) {
  this.path = path;
};

l1 = new Logger("/home");
console.log(l1);

l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);
```

Above solution works. However `l2` is a new instance of `Logger` .

## Singleton solution using a global variable

```javascript
window.global_logger = null;
var Logger = function (path) {
  if (global_logger) {
    console.log("global logger already present");
  } else {
    this.path = path;
    window.global_logger = this;
  }
  return window.global_logger;
};

l1 = new Logger("/home");
console.log(l1);

l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);
```

Above solution works. However this solution relies on creating a global
variable. To the extent possible it is best to avoid polluting global namespace.

## Single solution without polluting global namespace

```javascript
var Logger = (function () {
  var _instance;

  return function (path) {
    if (_instance) {
      console.log("an instance is already present");
    } else {
      this.path = path;
      _instance = this;
    }

    return _instance;
  };
})(); //note that it is self invoking function

var l1 = new Logger("/root");
console.log(l1);

var l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);
```

This solution does not pollute global namespace.

## Links

- [Human page](https://www.bigbinary.com/blog/singleton-function-in-javascript)
