JavaScript Global Variables
Last Updated :
12 Dec, 2024
Global variables in JavaScript are variables that can be accessed and modified from anywhere in the code, regardless of the scope where they were declared. These variables are stored in the global object (window in browsers and global in Node.js).
The declaration of global variables and accessing them.
JavaScript
// Global variable
let courseName = 'GeeksforGeeks';
function myFunction() {
console.log(courseName);
}
myFunction()
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 );
OutputGeeksforGeeks
GeeksforGeeks
Interesting facts about Global Objects
- Global Variables Are Part of the Global Object
JavaScript
var myVar = "Hello";
console.log(window.myVar);
- Undeclared Variables Become Global (in Non-Strict Mode)
JavaScript
function createGlobal() {
myGlobal = "I'm global!";
}
createGlobal();
console.log(myGlobal);
- Global Variables Can Be Overwritten
JavaScript
var appName = "MyApp";
// Another script overwrites it
var appName = "OtherApp";
console.log(appName);
- Strict Mode Restricts Globals
JavaScript
"use strict";
myGlobal = "Oops"; // ReferenceError: myGlobal is not defined
Advantages:
- Convenience: Easily share data across different parts of the application.
- Persistent Data: Retains value throughout the program’s execution.
Limitations of Global Variables
- Naming Conflicts: Variables with the same name can unintentionally overwrite each other.
- Debugging Challenges: It’s harder to trace changes to global variables.
- Memory Usage: Excessive use can lead to memory leaks, as global variables persist throughout the application’s lifecycle.
JavaScript Global Variables- FAQ’s
Do let and const create global variables?
Yes, but they don’t attach to the window object like var does.
What happens if you forget var, let, or const?
In non-strict mode, the variable becomes a global property of the window object.
Can global variables cause memory leaks?
Yes, because they persist until the program ends and are not garbage-collected.
Are global variables shared across scripts?
Yes, multiple scripts on the same page share the same global scope, leading to potential conflicts.
Can you accidentally overwrite a global variable?
Absolutely! Any script can redefine a global variable, causing unpredictable behavior.
Is window.myVar the same as myVar?
Only for var-declared globals, but not for let or const.
Does strict mode affect global variables?
Yes, strict mode prevents the creation of implicit global variables.