Global Scope and Functions, I need answers for this situation

Tell us what’s happening:
I tried to run it on jsbin and it doesn’t work, the only thing I see is “MyGlobal: 10” but when I delete fun1 and just leave “oopsGloba = 5;l” it runs perfectly.

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/77.0.126 Chrome/71.0.3578.126 Safari/537.36.

Hello @HQCuong,

Function fun2 checks whether your variable is undefined or not.
if myGlobal IS NOT undefined, it will give you its value.
if oopsGlobal IS NOT defined, it will give you this value.

You only get the value from myGlobal, which means that it IS NOT undefined.
You don’t get the value from oopsGlobal, it means that IT IS undefined.
There are two possibilities for that:

  1. it is not declared. To declare a variable you have to write: var nameOfVariable; and then you can assign a value: var nameOfVariable = value;
    Now, even if you do that inside fun1(), it will be undefined. Why?
  2. the scope. Functions are just like Las Vegas: what happens there, remains there! If you declare a variable inside a function, it is trapped inside and you can’t retrieve its value by just calling the variable.

If you want to oopsGlobal to be defined, you are going to have to declare it and give it a value outside of the function.

Hope it helps!
L.

1 Like

So it seems this lesson has a problem because they told me to create a variable inside fun1 without using ‘var’.

so, when you run this, do you call fun1() and then call fun2()? If fun1() is never being explicitly called, then your oopsGlobal is never being created.

And yes, by doing oopsGlobal = 5;, you are creating a global variable – not using var, let or const forces oopsGlobal to be created in the root, or window, scope.

1 Like

Oh, thank you, I got it.

Sorry, I didn’t know about that. I was just commenting on the code you displayed.
Hope I didn’t confuse you any further.
L.

2 Likes

No problem, I am very grateful that you tried to help.

1 Like