Why can't I declare multiple constants in JavaScript?

This is the correct syntax:

let foo, bar;

This is not true

const foo, bar;

Why is this?

And is there a way to declare multiple constants in one place and define them in another? Beyond the related declaration and definition.

+13
source share
5 answers

Because the const declaration must also be initialized. This will work:

 const foo = 1, bar = 2; 
+15
source

A normal variable (declared with var or let ) can be declared without a value, since you can assign them later:

 let foo; // foo has value undefined foo = 3; // foo has value 3 

However, you cannot do the same with constants, since you cannot change their value after they have been declared:

 const foo; // ...? foo = 3; // this is not allowed because foo is constant 

Therefore, you must simultaneously declare and assign a value to a constant. This can be done with several constants at the same time:

 const foo = 3, bar = 8; // this works fine, foo and bar are both constants 

There is no way to declare const in one place and assign it in another. Instead, you should use var or let .

+11
source

You can, but it's constant, so you need to assign them a value in the declaration

+2
source

const must be assigned a value when it is declared, as it makes it read-only.

0
source

const values ​​cannot be changed after assignment. You are trying to declare it now to change it later, which will not work with const . The solution to this problem is that you declare it with let or var .

0
source

Source: https://habr.com/ru/post/1258977/


All Articles