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?
Introduction to the JavaScript const keyword ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.
The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so.
A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error.
In C++ the const keyword has been improved and you can declare real const values. That's why it has to be initialized before compiling the code. The rule is slightly different: to be used in an integral constant expression, the initialization must be visible to the compiler.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With