Skip to content

JavaScript Global Scope | Basic code

  • by

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

let a = "Global Scope";

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

A variable declared outside of a function is considered a global scope variable. This variables 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, that variable automatically becomes a global variable.

function greet() {
    a = "hello"
}

greet();

console.log(a); // hello

Do 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

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.