Conditionally initializing a constant in 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)