JS question with declared and undeclared vars in/out of functions

Tell us what’s happening:

Hello Freecodecamp Community!

How come myVar = 10 is returning undefined in the console unless I declare it with var myVar = 10 But in the previous lesson (referenced with code below) oopsGlobal = 5 returned 5 in the console.

This is bugging me out lol

Your code so far

This Lesson:


function myLocalScope() {

// Only change code below this line
myVar = 10
console.log('inside myLocalScope', myVar);
}
myLocalScope();

// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);

Previous lesson:

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);
}
  **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.150 Safari/537.36.

Challenge: Local Scope and Functions

Link to the challenge:

It has to do with the concept of assignment.

You left out a/the crucial part of the previous challenge, and that is, that you first declare var oopsGlobal = 10 before the function, and only then you reassign it to 5.

Notice, how the important word here is written in bold: ‘reassign’.

In the previous challenge you basically told your computer this:
“Hey, there is this thing called oopsGlobal and it’s the same thing as 10.
Oh by the way, I also want you to do this thing: Remember oopsGlobal? Forget about what I just told you about it, because it’s actually the same thing as 5.”

Now in this challenge, if you don’t declare oopsGlobal using ‘var’, this is what you are telling the computer:
“I want you to do this thing: Remember myVar? …”
At which point your computer will go: “No, I don’t remeber myVar, you never said anything about it”

Hope this makes it clear :slight_smile: