0
request.onreadystatechange = function () {
  if (this.readyState === 4) {
    var nav = this.responseText;
  }
};

-->use nav here<--

How can I use my variable nav outside this function without being undefined?

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
DA123
  • 19
  • 1
  • 1
    Just declare `var nav;` without assigning it, outside the function. Where you assign it, remove `var` (just assign it). – user2740650 Dec 21 '20 at 20:43
  • Define it outside the function and set its value inside the function? Though you'll also need to keep in mind the asynchronous nature of what you're doing. – David Dec 21 '20 at 20:43
  • Declare it in the global scope and when you update it's value inside of the function. The global value will be updated. Remember don't declare it at both places if you will declare the variable in both scope the local one will be updated. Example - ```var a; function b() { a = 10; //Update it here } console.log(a); // 10 will be logged``` – Shreyash bhatt Dec 21 '20 at 20:44
  • 2
    You most likely can't get the value when you'd need it. See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323 – Teemu Dec 21 '20 at 20:45

0 Answers0