Query regarding FCC exercise

This FCC exercise states that:

Variables which are declared without the let or const keywords are automatically created in the global scope.

My takeaway from this sentence is that if I declare a variable with var, then it should be created in the global scope.

However, if I declare the oopsGlobal variable here with var, then this variable is not being treated as a global variable by the FCC console:

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

function fun1() {
  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);
}

The output for this code is being shown as:
myGlobal: 10

which means that oopsGlobal is NOT global, instead of

myGlobal: 10 oopsGlobal: 5

which would have been the case if oopsGlobal were indeed global.

Can someone please confirm that if a variable is declared using var, it is indeed created in global scope? Or am I missing something else here?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope

(quoted from the internet)

Looks like var makes variables global but not if they are inside a function already.

var globalVar1 = 'I am a globally scoped variable';

let globalVar2 = 'I am a globally scoped variable';

const globalVar3 = 'I am a globally scoped variable';

function test() {
  globalVar4 = 'I am a globally scoped variable';

  var localVar = 'I am a variable with local scope to this function';

  let localVar2 = 'I am a variable with local scope to this function';

  const localVar3 = 'I am a  variable with local scope to this function';
}
1 Like

This was super helpful - thanks!

1 Like