DEV Community

Randy Rivera
Randy Rivera

Posted on

Global/Local Scope and Functions.

Global Scope and Functions

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

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

  • Example:
var myGlobal = 10; // this is a Global Scope

function some1() {
otherGlobal = 5; // this is also a Global Scope since it's not defined within the function.
}

function some2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof otherGlobal != "undefined") {
    output += " otherGlobal: " + otherGlobal;
  }
  console.log(output);
}
// don't worry about the rest of the code for now, you'll learn it as you go and I'll be here to see it through.
Enter fullscreen mode Exit fullscreen mode

So here we are using var declaring a global variable named myGlobal outside of any function. we initialized it with a value of 10.

Inside function some1, we assigned 5 to otherGlobal without using the var keyword.

Local Scope and Functions

Variables which are declared within a function, as well as the function parameters, have local scope. That means they are only visible within that function.

  • Here is a function myTutorial with a local variable called myVar.
function myTutorial() {
  var myVar = "food";
  console.log(myVar);
}
myTutorial(); // will display food
console.log(myVar); // will display ReferenceError: myVar is not defined
Enter fullscreen mode Exit fullscreen mode

The myTutorial() function call will display the string food in the console. The console.log(myVar) line will throw an error, as myVar is not defined outside of the function.

Global vs. Local Scope in Functions

It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.

  • For example:
var consoleSystem = "Xbox";

function mySystem() {
  var consoleSystem = "PS5";
  return consoleSystem;
}

mySystem(); // will display PS5
console.log(consoleSystem); // will display Xbox because it is a variable that is defined outside of a function block (Global Scope)
Enter fullscreen mode Exit fullscreen mode

The function mySystem will return the string PS5 because the local version of the variable is present.

Top comments (0)