Testing: Global Scope and Functions in Repl.it

I am struggling to understand the concepts in this lesson. I understand how it all therotically works, however when I run the code in the Repl.it environment, it comes back as undefined. Shouldn’t the quiz return the value of the output rather than being undefined?

There is probably a very simple answer but I have read/ searched with no luck. Here is my code.

// 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);
}

Thanks. Noted for future

So when I call the fun2 function, I get the result myGlobal = 10. Why is it that when I call the fun1() function, it is not defined? Thanks for your reply

So to confirm, the reason fun2() funtion prints the result of "myGlobal: " + myGlobal; vs " oopsGlobal: " + oopsGlobal is because the var MyGlobal value of 10 overrides the oopsGlobal value of 5. Is this correct?

I am just confused because “Variables which are used without the var keyword are automatically created in the global scope.” Under this logic, I just thought it would print the oopsGlobal value.

Thats what I thought should happen. But when I call fun1(), it returns undefined value.

I understand! Thanks you so much for taking the time to explain. Much appreciated :slight_smile: