JavaScript Global Scope

You are Here:

What is Scope?

Scope determines the availability (visibility, or accessibility) of variables.

Types of Scope

There are two types of scope available in JavaScript, they are

  • Global Scope
  • Local Scope

Global Scope

When a variable is declared outside a function, then the variable is said to be Global.

Global variable is accessible for all scripts and functions on a web page.


HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> // Global variables var x = document.getElementById("point"); var txt = "Hello"; function myFunction(){ x.innerText = txt; } myFunction(); </script> </body> </html>

External Global Scope


The following is the variable.js JavaScript file.

var txt = "Hello";

Accessing the above global variable txt by including the source path in the script tag.

Note: The external file should be included before the calling of the variable.

HTML Online Editor
<!DOCTYPE html> <html> <head> <script src="/variable.js"></script> </head> <body> <p>variable 'txt' is in "/variable.js" external file.</p> <p id="point"></p> <script> var x = document.getElementById("point"); function myFunction(){ // Accessing GLOBAL variable x.innerText = txt; } myFunction(); </script> </body> </html>

Automatically Global

When you assign a value to a variable (inside a functon) that has not been declared, it will automatically become a GLOBAL variable.


HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); function myFunction(){ // Becomes GLOBAL variable txt = "Hello"; } myFunction(); x.innerHTML = txt; </script> </body> </html>


Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author