Reputation: 671
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?
Upvotes: 6
Views: 29693
Reputation: 780798
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));
Upvotes: 4
Reputation: 1795
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
Upvotes: 2
Reputation: 1332
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.
Upvotes: 0
Reputation: 324
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 = [];
Upvotes: 3