JS first exercise in Variable Scope

Tell us what’s happening:
Your exercise seems to imply that by excluding the keyword var the variable you create inside a function that it becomes a global variable. When in fact oopsGlobal is already declared but simply not visible in the code.

Please add the oopsGlobal declaration on the code so it isn’t as confusing

Your code so far


// Declare the myGlobal variable below this line
var myGlobal = 10; 

function fun1() {
oopsGlobal = 5;// Assign 5 to oopsGlobal Here
randomVar = 2;//this is wrong if you haven't declared it before
var randomVar = 2;// if I create a var here its Local
}

// Only change code above this line

function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
  output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
  output += " oopsGlobal: " + oopsGlobal;
}
if (typeof randomVar!= "undefined") { //this one doesn't show up
  output += " oopsGlobal: " + randomVar;
}
console.log(output);
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0.

Challenge: Global Scope and Functions

Link to the challenge:

No it isn’t, that’s the point.

It doesn’t imply it, it clearly states it: this is how JS works (and is a primary reason why “strict mode” and the new variable keywords were added to the language, to fix this behaviour)

Ok now I’m a bit confused can you elaborate on that?

Because if I remove var from randomVar or any other made up var it throws:
ReferenceError: assignment to undeclared variable randomVar

You’re adding random other things into the code, the tests are specifically constrained to deal with what is described in the challenge overview and cannot understand what those things are. So you will get errors.

This is not a full environment, it’s something designed to demonstrate one single concept. At this point in the curriculum, you can’t generally just add arbitrary JavaScript and run it. If you want to do that, use the browser’s built in console

If you declare a variable without the var keyword, it automatically becomes global.