Declaring variables in an API call

Declaring variables in an API call
0

#1
<script>
  document.addEventListener('DOMContentLoaded',function(){
    document.getElementById('getMessage').onclick=function(){
      req=new XMLHttpRequest();
      req.open("GET",'/json/cats.json',true);
      req.send();
      req.onload=function(){
        json=JSON.parse(req.responseText);
        document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
        // Add your code below this line
        
        
        // Add your code above this line
      };
    };
  });
</script>

My question is pretty simple. Why can we use req=new without first declaring req? I would expect this code to error ‘req is not defined’ but it functions


#2

Why can we use req=new without first declaring req?

This is a “feature” in JavaScript.

The simple answer:
Not appending the var keyword to a variable will cause it to be a global object. (i.e. window object)

The more accurate answer:

If you use var the variable is declared within the scope you are in (e.g. of the function). If you don’t use var , the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser).

Example: with var

var n = 1;

console.log(n);   // => 1
console.log(x()); // => 0
console.log(n);   // => 1

function x () {
  var n = 0;
  return n;
}

Example: without var

var n = 1;

console.log(n);   // => 1
console.log(x()); // => 0
console.log(n);   // => 0

function x () {
  n = 0;
  return n;
}

I would expect this code to error ‘req is not defined’ but it functions

My guess JavaScript is not your first language. But nonetheless, you should avoid declaring variables this way as it make things harder to debug and maintain.


#3

to be clear, I have been delcaring variables using let.

The above code I pasted is what they give you in the challenge