Skip to content

JavaScript Global Scope | Basic code

  • by

Global Scope means the defined data type can be accessed anywhere in a JavaScript program. JavaScript Global Scope concept is related to Variables.

let a = "Global Scope";

function greet () {
    console.log(a);
}

A variable declared outside of a function is considered a global scope variable. This variable can be accessed from anywhere in a JavaScript program.

JavaScript Global Scope

Simple example variables declared with var, let and const are quite similar when declared outside a block.

<!DOCTYPE html>
<html>
<body>
  <script>    
    var x = "Global";
    let y = "Scoop";
    const z = "Example";

    function print(){
      console.log(x,y,z)
    }
    print();
  </script>  

</body>
</html>

Output:

JavaScript Global Scope

The value of a global variable can be changed inside a function.

<script>    
    let a = "Hello";

    function greet() {
      a = 100;
    }

    console.log(a);

    greet();
    console.log(a); 
</script> 

Output:

Hello
100

If a variable is used without declaring it, it automatically becomes a global variable.

function greet() {
    a = "hello"
}

greet();

console.log(a); // hello

Here’s an example of global scope:

// Global variable
var globalVar = "I am a global variable";

function exampleFunction() {
  // Accessing the global variable within a function
  console.log(globalVar);

  // Creating a local variable within the function
  var localVar = "I am a local variable";

  // Accessing the local variable
  console.log(localVar);
}

// Calling the function
exampleFunction();

// Accessing the global variable outside the function
console.log(globalVar);

// Attempting to access the local variable outside the function will result in an error
// console.log(localVar); // This line will cause an error

In this example, globalVar is declared outside any function, making it a global variable. The exampleFunction function can access both the global variable and its own local variable (localVar). However, attempting to access the local variable outside the function results in an error because it’s limited to the scope of the function.

Comment if you have any doubts or suggestions on this JS scope topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *