5

In javascript, as per my understanding, we can declare variables with let and var keywords and assign it a value later.

var a;
a = 5;

But, when I try the same approach with const keyword it does not work.

const a;
Uncaught SyntaxError: Missing initializer in const declaration

I understand my question has a basic contradiction because const keywords are used for storing immutable variables. Therefore, a good coding practice may require it to be initialized while being declared.

However, I want to store global value in a const variable that is being fetched by an API. So, I was wondering if there is a way to assign a value to a pre-declared const variable in javascript?

Aditeya Pandey
  • 661
  • 2
  • 6
  • 13
  • 4
    What sense does it make? You can't reassign a `const` variable. If you declare it without a value, how would you give it a value later? – Barmar Jan 22 '20 at 23:47
  • You may be thinking of `declare` https://stackoverflow.com/questions/49745860/what-is-declare-var-in-node-js – Seph Reed Jan 22 '20 at 23:48
  • 1
    `const` doesn't mean the value is immutable, it means the variable is immutable. – Barmar Jan 22 '20 at 23:48
  • I agree with you, it might not be the right practice. However, I was wondering if there is a clever way to store values fetched by api's in vanilla javascript as const global variables. – Aditeya Pandey Jan 22 '20 at 23:50
  • @AditeyaPandey No, there's not (without `eval`) – Bergi Jan 22 '20 at 23:51
  • 1
    The proper way to solve this is to store a promise for the response in the global constant. – Bergi Jan 22 '20 at 23:52

4 Answers4

3

Have two ways to create a const with default value, 1 object with properties mutable, 2 array, as you can see bellow.

const a = {};
cosnt b = [];
Matheus Frez
  • 324
  • 2
  • 7
3

const applies to the variable, not the value. You have to initialize them, because you can't assign them later -- that's the only difference they have. You can't have a variable that you can assign just once, but not reassign.

If the result is an object, you can declare the constant to hold an empty object, and then use Object.assign() to fill it in with the API response.

const result = {};
fetch(...).then(response => response.json()).then(data => Object.assign(result, data));
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

I think you can not do that way . In JavaScript const variables must be assigned a value when they are declared:

Incorrect

const PI;
PI = 3.14159265359;

Correct

const PI = 3.14159265359;

For more reference you can take a look at this which gives you a better explanation

https://www.w3schools.com/js/js_const.asp

Amit Sharma
  • 1,775
  • 3
  • 11
  • 20
0

You can't do so, at least not in run-time. I suggest you consider using TypeScript, which has the readonly modifier which will help you protect your variable from being overwritten during compile-time.

Amit Beckenstein
  • 1,220
  • 12
  • 20