Variable inside a Variable, not updating

36 Views Asked by At

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.

1

There are 1 best solutions below

0
Simon Lundberg On BEST ANSWER

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"