It seems like the only variable accepted here is myGlobal & oopsGlobal. Bcz when I tried to substitute all the oopsGlobal with something else like opsGlobal, I don’t get any output.
Here I’m getting the expected output: myGlobal: 10 oopsGlobal: 5
var myGlobal = 10;
function fun1() {
oopsGlobal = 5
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
But here the output shows ReferenceError: opsGlobal is not defined
var myGlobal = 10;
function fun1() {
opsGlobal = 5
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof opsGlobal != "undefined") {
output += " opsGlobal: " + opsGlobal;
}
console.log(output);
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78
I’d recommend not to do these experiments inside the FCC challenge editor. It does stuff under the hood that you can’t see.
The challenge editor runs in strict mode, which causes an error whenever your declare a variabe without keyword. I suspect that for this challenge, there’s something happening behind the scenes to prevent that error to be thrown, but only if that variable is called oopsGlobal. That’s why you get different results when you enter the exact same code, just with a different variable name.
To avoid confusion and to get an idea of what’s really happening in a browser, use an editor of your choice and run that code locally on your computer, with no FCC setup doing some secret magic that messes with your results.
It is not an stupid question at all. In fact, it is pretty interesting. What this challenge tries to teach you if that you can reassign variable values.
If you use other keyword than oopsGlobal, that variable is undeclared, so you can’t reassign its value.
Checking the “behind the scenes” code for this challenge, it declares that variable for you in the “”“glogal”"" scope before it runs, so @jsdisco was right. Imagine that there is an extra line before your first line of code, with var oopsGlobal;
Just focus on:
You can declare variables on different scopes.
You can reassing variables if that variable exists on your scope.