Declaring variables in an API call

<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

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.

1 Like

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

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