Correct.
Ok. Looking at the complete solution:
var myGlobal = 10; // <-- global variable
function fun1() {
oopsGlobal = 5; // <-- unintended global variable
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
The point is that oopsGlobal
should not be available in fun2()
. If oopsGlobal
was defined correctly using the var keyword in fun1()
, then fun2()
would not be able to access it because it is inside fun1()
's scope. The typeof conditional statements are just there to check if fun2()
has access to oopsGlobal
.
function fun2() {
var output = ""; // this is what is logged to the console
// myGlobal should not be undefined
// because it is in the global scope and we can access it.
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
// oopsGlobal should be undefined because it is inside a different function.
// unfortunately due to error, it was put in the global scope.
// Because it is in the global scope, it is not undefined and we log the value (5)
// to the console.
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output); // myGlobal: 10 oopsGlobal: 5
}
If we had done it correctly, the code would be like this:
var myGlobal = 10; // <-- global variable
function fun1() {
var oopsGlobal = 5; // <-- function only variable
}
function fun2() {
var output = "";
// myGlobal is not undefined - log it to the console
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
// oopsGlobal is undefined - therefore we will not return it to console.
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output); // myGlobal: 10
}