Home > Mobile >  Should I use let or var when implementing a singleton?
Should I use let or var when implementing a singleton?

Time:11-12

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?

CodePudding user response:

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.

CodePudding user response:

In case to choose between 'var' or 'let' the best choice is 'let' because one of the differences it that 'let' removes the error-prone behavior with variable hoisting, you can read this for specifications: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let. But you should consider using only const as your default variables because the majority of bugs out there involve unexpected state changes, everything you can use to guarantee variable values and states should be used to avoid this kind of most commum problems.

CodePudding user response:

You've already consider to use const instead?

I've always used const and never had a problem, because you'll never reassing the entire object.

  • Related