Mikael
Mikael

Reputation: 191

How can I assign a value to a constant variable (not in declaration)?

I want to have a constant variable (globally) that can hold a node, however I don't know the value of that node yet! So I have to wait until a specific function is called to get the value that need to be assigned to my global constant.

Below is my current code:

var counter = 0;
let myConstVar; // THIS VARIABLE need to be constant

function FunctionToBeCalled(name){

    //some code

    if(counter==1){
        var myNode = document.getElementById(name);
        myConstVar = myNode.cloneNode(true);
    }

    //some code
}

function Caller(aName){

    //some code

     counter++;
    FunctionToBeCalled(aName);

//some code that will change the behavior of the each node with ID "aName"
}

then I call the function Caller several times (each time I press a button).

The code that I have above works, but it gives different value, as each time I enter FunctionToBeCalled the value of myConstVariable changes.

So I really need to set the variable myConstVar as const to save its value (which is the first node I get from calling FunctionToBeCalled), so that I can use it and assign it to another variable later.

Upvotes: 1

Views: 1740

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Actually if the value will be available somewhen, a Promise is an appropriate datastructure to keep it:

 const node = new Promise((resolve) => {
   if (document.readyState !== 'loading') {
     return resolve(document.getElementById(name).cloneNode(true));
   }
   document.addEventListener("DOMContentLoaded", () => {
     resolve(document.getElementById(name).cloneNode(true));
   });
});

That way, the variable can be constant and can't be changed, and the resolution is tied to the declaration.

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

I would recommend against global variables, but you can define a getter on the global object:

Object.defineProperty(globalThis, "myConstVar", {
  get() { 
    return myNode;
  }
  writable: false, // can't mutate this
  configurable: false
});

This would make the global "myConstVar" have that value from that point on and it won't be possible to change it.

Upvotes: 2

Related Questions