<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
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.