0

I have a question about the if a variable value persist between different calls.

I have a file called shared.ts which contains a variable isSignIn and a function signIn like below:

let isSignIn = false 

export function signIn() {   
  if (isSignIn) {
     // do nothing 
  }   else {
    // do actual sign in  
  } 
}

This signIn function is called by other files. During tests, it seems the value of isSignIn persist between different calls. I would like to know why.

bunny
  • 1,797
  • 8
  • 29
  • 58
  • 1
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Klaycon Nov 27 '19 at 19:57
  • Why would it not persist? Guessing I am missing why you would think the value would/would not persist. – epascarello Nov 27 '19 at 20:02
  • I think it is a global variable inside this shared.js file. Every time a call from other files call this function, isSignIn should be set to its initial value which false. Does javascript maintain its state somewhere so that it persist? – bunny Nov 27 '19 at 20:05
  • 1
    When a file is required, it is cached. Since this file exports a function (and, as per the linked dupe target, the function's closure), every time the file is required the same cached copy is returned with references to the same portions of memory. This is required for modules to have consistent behavior when needed in multiple files. – Klaycon Nov 27 '19 at 20:06
  • I see. I also tried to modify the value of this variable in other files by exporting it and import it in other files. It is importalble, however, it gives me error like this: 'Cannot assign to 'isSignIn' because it is not a variable' when I tried to assign a new value to it. Why is that? – bunny Nov 27 '19 at 20:09
  • 1
    Imported values are read-only. If you'd like to modify state in the file, you can export an object containing `isSignIn` - you should be able to change it then. Failing that, export a function that modifies the value. – Klaycon Nov 27 '19 at 20:12
  • Right now I use the second approach to export a function that modifies the value. Thank you so much! – bunny Nov 27 '19 at 20:13

0 Answers0