Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
Frozen Crayon Avatar asked Aug 04 '16 10:08

Frozen Crayon


People also ask

How do you declare constants in JavaScript?

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.

Can you change a constant in JavaScript?

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.

How do you declare a constant object?

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.

Is it necessary to initialize const variables?

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.


1 Answers

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.

like image 78
Hecksa Avatar answered Oct 05 '22 14:10

Hecksa