Conditionally initializing a constant in Javascript

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?


Solution 1:

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:

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:

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

const x = condition ? 5 : 10;