Search code examples
javascriptnode.jssingletoncommonjs

Should I use let or var when implementing a singleton?


I understand the difference between both (let locks the reference inside the block, whereas var declares a variable accessible scope-wide).

But considering the singleton pattern module-based:

var singleton = null;

module.exports = () => singleton ? singleton : singleton = newInstance();

Should I declare the singleton variable with let or var ? Is there any difference, considering CommonJS module imports/exports?


Solution

  • There is no difference between let or var, when we are talking about singleton implementation. I have already checked it in my IDE. Considering that using "let" is better practice, I suggest you to use exactly "let" keyword.