0

Running this code in console gives an error: Cannot read property 'status' of undefined.

xhr = new XMLHttpRequest(); // global variable
xhr.open('GET', '/');
xhr.onload = function(){
    console.log(xhr.status); // this line throws the error
    var xhr = 'a'; // local variable
}
xhr.send();

If I comment out the line var xhr = 'a';, it works. Can someone explain what happens here?

Tested in Chrome and Firefox.

Marko
  • 803
  • 9
  • 13
  • 1
    When you reference a name, you’re referencing the one in the closest scope, even if the line with the `var` (or `let`, `const`, or `function`) is after the reference. That the reference is valid with `var` is known as “hoisting”. If you have the browser support, use `let` (and never `var`, anywhere) to get a better error. – Ry- Apr 06 '20 at 11:56
  • @Ry- I don' think that's it. Try changing console.log(xhr.status) to console.log(xhr). It should print 'a', but it doesn't. – Marko Apr 06 '20 at 11:59
  • The declaration is hoisted, but the assignment isn’t. It acts like `var xhr; console.log(xhr.status); xhr = 'a';`. If this behaviour strikes you as never useful, you’re not wrong, which is why it was fixed with `let`. – Ry- Apr 06 '20 at 12:00
  • @Ry- yeah I was trying to figure out when it can be useful but cannot think of any case.. Thanks! – Marko Apr 06 '20 at 12:13

0 Answers0