close
The Wayback Machine - https://web.archive.org/web/20240225000510/https://www.geeksforgeeks.org/javascript-global-variables/
Open In App
Related Articles

JavaScript Global Variables

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

What are global variables in JavaScript?

JavaScript Global Variables can be accessed outside any function or block. JavaScript global variables are declared within the window object or outside any block or scope.

A variable declared without a keyword is also considered global even though it is declared in the function.

Below are some examples to see the declaration and use of JavaScript global variables.

 

Example 1: In this example, we will see the declaration of global variables and accessing them.

Javascript

// Global variable
let courseName = 'GeeksforGeeks';
  
function myFunction() {
    console.log(courseName);
}
  
myFunction()

                    

Output
GeeksforGeeks

Example 2: In this example, we will declare a global variable inside a function and access it outside that function.

Javascript

function myFunction() {
  
    // Considered global
    courseName = 'GeeksforGeeks';
    console.log( courseName );
}
  
myFunction();
  
console.log( courseName );

                    

Output
GeeksforGeeks
GeeksforGeeks


Last Updated : 02 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads