Tell us what’s happening:
It isn’t working so please help because it says
oopsGlobal should be a global variable and have a value of 5
Your code so far
// Declare the myGlobal variable below this line
var myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
var 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 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15
.
Challenge: Global Scope and Functions
// Declare the myGlobal variable below this line
var myGlobal = 10;
var oopsGlobal
function fun1() {
// Assign 5 to oopsGlobal Here
var 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);
}
To declare a global variable inside of a function you must omit “var”.
For example:
// Declare the myGlobal variable below this line
var myGlobal = 10;
function fun1(){
// Assign 5 to oopsGlobal here
oopsGlobal = 5;
}
When you declare a variable inside of a function using “var”, it automatically makes the variable local to that function. When you omit “var” the variable is global in scope.
Protip: You do not want to declare global variables inside of a function. Just don’t. I believe that these challenges go on to show why this gets messy.
1 Like