Global Scope and Functions var

Tell us what’s happening:

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.

  • this is old information. I suggest this and similar parts of the course be updated for ES6. It’s 3 years old already and is now widely supported.

Your code so far


// Declare your variable here


function fun1() {
  // Assign 5 to oopsGlobal Here
  
}

// 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; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:

Hi @MomchilDeus

Whilst ES6 may not be so new anymore, there are still plenty of browsers still in use by people that don’t support it. Given your life as a developer will probably include maintaining these older code bases (I’m currently doing that right now), this knowledge is vital imo.

Plus, ES6 has a separate part of the curriculum that covers block scoped variables.

1 Like

Hey Joe,

I agree. I still do support those when needed, all I’m saying is that this statement:

Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

is no longer definitely true and someone might get confused later on. :slight_smile: