Conditionally initialization of a constant in Javascript

ES6 onwards 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 a constant before initializing it.

But if I do

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

x becomes blocky.

So how to conditionally create a constant?

+8
javascript ecmascript-6 constants
source share
4 answers

Your problem, as you know, is that const must be indexed in the same statement in which it was declared.

This does not mean that the value you assign to the constant must be literal. It can be any valid statement truly - a threefold:

 const x = IsSomeValueTrue() ? 1 : 2; 

Or maybe just assign it to a variable value?

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

Of course, you can assign it to the return value of the function:

 function getConstantValue() { return 3; } const x = getConstantValue(); 

Thus, there are many ways to make a value dynamic; you just need to make sure that it is assigned in only one place.

+11
source share

If the ternary operator is not an option for its unreadability, the only option is IIFE, which is cumbersome but can be easily read:

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

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

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

From my personal experience ~ 95% of const variables. If the variable should be let , just let it be; the probability of errors caused by random reassignments is negligible.

+5
source share

Assuming that const will be declared in instances , you can use triple assignment:

 const x = condition ? 5 : 10; 
+3
source share

I propose this solution using the Singleton Pattern :

 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(); 
0
source share

All Articles