1

Good day legendaries, I am Nodejs and Javascript newbie.

I have routes getting value from a common variable that is on top of them.

let commonVariable = "theDefaultValue";

//some route just to get commonVariable value
route.get("/", async (res, req) => {
});

//some routes below that change commonVariable value
route.post("/", async (res, req) => {
  //changing commonVariable value
  commonVariable = "anotherValue";
})

My concern is, how is the value of commonVariable after some routes change it, will other routes get the original value?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Aljohn Yamaro
  • 2,629
  • 25
  • 22
  • 1
    If there's one relatively-global variable, then it can only have one value at a time, so no, other routes will not get the original value. – Pointy Aug 31 '19 at 15:54
  • It has nothing to do with routes and depends on how you access your variable. The variable name is just like like a named box, and accessing a variable is like saying "hey, give me whatever is inside box X", if someone else changes the contents of that boxevery one will see the new value, as the old content will be discarded (garbage collected). – XCS Aug 31 '19 at 15:54
  • 2
    *"...will other routes get the original value?"* No, they'll get the current value, the updated one. See the [linked question's](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) answers for details. Your route handler functions are *closures* over the context where `commonVariable` is declared. – T.J. Crowder Aug 31 '19 at 15:57
  • @T.J.Crowder sir my account is blocked from asking another question, i don't know that is a duplicate one, I tried to search and look to auto-generated suggestion but found nothing and you came and mark with duplicate T_T .Anyway thank you for your answer that help me – Aljohn Yamaro Aug 31 '19 at 16:03
  • As I understand it, closing as a duplicate is not a significant part of the question ban algorithm: https://meta.stackexchange.com/a/259927/134069 – T.J. Crowder Aug 31 '19 at 16:19

0 Answers0