Singeltons in JavaScript not needed?

decker67

decker

Posted on August 20, 2022

Singeltons in JavaScript not needed?

Yes you can implement the singelton pattern in JavaScript with a class, but is it useful or do we need it?

I don't think so, because simply using an object literal is sufficient and always a singelton, if you place it in his own file.

This little example shows it.

console.log('A imported')

const state = {
  isLoading: false,
  hasError: false
}

export default state
Enter fullscreen mode Exit fullscreen mode
import state from './A.js'
console.log('B imported')

const api = {
  getData () {
    state.isLoading = true
  }
}

export default api

Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <script type="module">
    import state from './A.js'
    import api from './B.js'
    console.log(state)
    api.getData()
    console.log(state)
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The console shows only one A imported and the state is shared.

Image description

The reason is, JavaScript imports each file/module only once and modules are singletons per definition. If a module is imported multiple times, only a single instance of it exists and it is evaluated only once after load.

💖 💪 🙅 🚩
decker67
decker

Posted on August 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Singeltons in JavaScript not needed?
javascript Singeltons in JavaScript not needed?

August 20, 2022