Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable inside a Variable, not updating

I am making a java script in which I need to occasionally change the headers of a specific request, however the token I am passing vs what i need it to be is not changing. (from what I can see) (sorry for the terrible explanation, I don’t even know what I’m doing to be honest.)
Example:
var abc23token = token1
shortly after, in the beginning of the script

var headers = {
  headers: {
    'Authorization': abc23token, // SHOULD change
    'Content-Type': 'application/json' // doesnt change
  }
}

Then, wayyy later in the script
abc23token = token2
however, the request still sends as token1.
token1 and token2 ARE variables, shouldn’t matter as its just a string like this

var token1 = "OT...Q"
var token2 = "OD...yE"

do i have to redefine headers? should I just ditch the idea of using a variable for tokens and use a plain string for abc23token?
please note that i don’t use javascript very much and I am very much a noob at this, and I apologize if this question is completely stupid or if its inefficient to do it this way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In JavaScript, there are fundamentally two types of entities: primitives and objects. Primitives can be reassigned, but they cannot be altered.

Primitives include things like numbers and strings.

Objects are things like, well, Objects (written like {key: value}), arrays ([1, 2, 3, ...]).

For example, some primitives:

let a = "hello";
let b = a; // b is now "hello"

a = "bye"; // a is now "bye", but 
           // b is is still "hello"

Objects, on the other hand, can be altered, and that change is reflected across all variables that reference that object:

let a = {
    phrase: "hello"
};

let b = a;
a.phrase = "bye"; // b.phrase is now "bye"

It also means that this doesn’t work the way you might expect:

let obj = {
    token: "hello"
}

let token = obj.token;
token = "bye"; // obj.token is still "hello"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading