0

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.

  • When you say someone you refers to other developers in your application or the user? because in the second case you should assume that he can always change the javascript code, by breakpoints and code injections – Greedo Jul 06 '21 at 14:32
  • JavaScript runs on the client. The client can do anything with it. Nothing can prevent that. You can make it harder, but this also makes it harder for you. – Andreas Jul 06 '21 at 14:36

0 Answers0