how you doing? I wondered, there is a way to declare an immutable variable (like the const keyword) in js, but assign the value just one time after maybe an ajax request or a fetch?
My problem is quite simple: I've 3 _id that I need to retrieve from my server when the document is on load and I need to store them inside some global variable. I need these 3 _ids to be unmutable, because all the next ajax requests on the site rely on these, and I cannot let someone change the value inside those variables.
Const keywords are perfect, but I don´t have the scope to use them or I cannot declare the variable before the ajax request.
There's a workaround?
const _id1 = null; // Correct, but this means nothing to me
const _id2; // Error: Missing initializer in const declaration
let _id_3 = null; // Formally correct, I can assign a new value to the variable
// but everybody can modify it from the console...
// What I need to do is
// 1) declare the variable
let magic_id;
// 2) do my ajax calls to my server
$.ajax({
url, data, type, ...,
success(payload){
// 3) Assign the value to my id
let aPay = JSON.parse(payload);
magic_id = aPay._id;
}
});
// 4) If someone tries to assign a new value i need to prevent it
magic_id = new_value; // Uncaught TypeError: Assignment to constant variable.