Conditionally initializing a constant in Javascript

JavascriptEcmascript 6Constants

Javascript Problem Overview


ES6 onwards we have const.

This is not allowed:

const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;

This makes sense because it prevents us from using the constant before it's initialized.

But if I do

if(condition)
    const x = 5;

else 
    const x = 10;

x becomes block scoped.

So how to conditionally create a constant?

Javascript Solutions


Solution 1 - Javascript

Your problem, as you know, is that a const has to be intialised in the same expression that it was declared in.

This doesn't mean that the value you assign to your constant has to be a literal value. It could be any valid expression really - ternary:

const x = IsSomeValueTrue() ? 1 : 2;

Or maybe just assign it to the value of a variable?

let y = 1;
if(IsSomeValueTrue()) {
    y = 2;
}

const x = y;

You could of course assign it to the return value of a function, too:

function getConstantValue() {
	return 3;
}

const x = getConstantValue();

So there's plenty of ways to make the value dynamic, you just have to make sure it's only assigned in one place.

Solution 2 - Javascript

If ternary operator isn't an option for its unreadability, the only other option is IIFE, which is cumbersome but can be read fluently:

const x = (() => {
  if (condition)
    return 5
  else
    return 10
})();

The semantics of const is that it is assigned once. It should be let for this use case:

let x;
if(condition) x = 5;
else x = 10;

From my personal experience, ~95% of variables are const. If a variable has to be be let, just let it be itself; the probability of bugs caused by accidental reassignments is negligible.

Solution 3 - Javascript

Assuming that the const is going to be declared in both instances, you could use a ternary assignment:

const x = condition ? 5 : 10;

Solution 4 - Javascript

I suggest this solution with a Singleton Pattern implementation:

var Singleton = (function () {
    var instance;

    function createInstance() {
		// all your logic here
		// so based on your example:
		// if(condition) return 5;
		// else return 10;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

const x = Singleton.getInstance();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrozen CrayonView Question on Stackoverflow
Solution 1 - JavascriptHecksaView Answer on Stackoverflow
Solution 2 - JavascriptEstus FlaskView Answer on Stackoverflow
Solution 3 - JavascriptCodingIntrigueView Answer on Stackoverflow
Solution 4 - JavascriptAla Eddine JEBALIView Answer on Stackoverflow