JavaScript: Global Scope and Functions Excercise

JavaScript: Global Scope and Functions Excercise
0.0 0

#1

JS%20Questiona

In The above snapshot, If I understand correctly it should say “declare” rather than “use”? (I ask - because it’s confusing)

In the Excercise: Why the following function gives an output, given that there is no function call?

// Declare your variable here
var myGlobal = 10;



function fun1() {
  // Assign 5 to oopsGlobal Here
  oopsGlobal = 5;  
}



// Only change code above this line
function fun2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}


#2

If oopsGlobal had been declared with var, it wouldn’t have been accessible by fun2() at the bottom, because it would be confined to the scope of fun1(). It would return an error: Uncaught ReferenceError: oopsGlobal is not defined.

>  var myGlobal = 10;
>  function fun1() {
   var oopsGlobal = 5;
   }
>  console.log(myGlobal)
< 10
> console.log(oopsGlobal)
VM377:1 Uncaught ReferenceError: oopsGlobal is not defined

But without declaring with var:

...
> console.log(oopsGlobal)
< 5

I see how that could be confusing. Their wording is technically correct, because in this case you’re using it without ever having declared it. When that happens, JavaScript basically figures out what it is based on context.