Scope of variables...urgent!

Tell us what’s happening:
Why does function fun2() prints only the value of “myGlobal” when called without calling function fun1()?? Also the same happens when fun1() is called after fun2() as shown in the code below… The value of variable “oopsGlobal” is not displayed.

Your code so far


// Declare the myGlobal variable below this line
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);
}
fun2();
fun1();

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36.

Challenge: Global Scope and Functions

Link to the challenge:

1 Like

oopsGlobal is defined before the code is run, hoisted to the top, but the value is assigned only when fun1 is called, before that it is undefined

1 Like