Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the lifetime of JavaScript variables?
The lifetime of a JavaScript variable refers to how long it exists in memory, from creation to destruction. Variable lifetime depends on scope and the execution context where it's declared.
Local Variable Lifetime
Local variables are created when a function is called and destroyed when the function completes execution. They exist only within their function scope.
<html>
<body>
<script>
function checkScope() {
var localVar = "I'm local"; // Created when function starts
console.log(localVar);
// localVar is destroyed when function ends
}
checkScope();
// console.log(localVar); // Error: localVar is not defined
</script>
</body>
</html>
I'm local
Global Variable Lifetime
Global variables are created when declared and persist until the page is refreshed or the browser window/tab is closed. They remain accessible throughout the entire program execution.
<html>
<body>
<script>
var globalVar = "I'm global"; // Lives throughout page lifetime
function accessGlobal() {
console.log(globalVar); // Can access global variable
var localVar = "local"; // Dies when function ends
}
console.log(globalVar); // Accessible here
accessGlobal();
console.log(globalVar); // Still accessible
</script>
</body>
</html>
I'm global I'm global I'm global
Variable Shadowing Example
When local and global variables have the same name, the local variable "shadows" the global one within its scope.
<html>
<body>
<script>
var myVar = "global"; // Global variable
function checkScope() {
var myVar = "local"; // Local variable shadows global
console.log(myVar); // Prints local value
}
console.log(myVar); // Prints global value
checkScope(); // Prints local value
console.log(myVar); // Prints global value again
</script>
</body>
</html>
global local global
Variable Lifetime Comparison
| Variable Type | Created When | Destroyed When | Scope |
|---|---|---|---|
| Global | When declared | Page unload/refresh | Entire program |
| Local | Function call | Function completion | Within function only |
| Function Parameter | Function call | Function completion | Within function only |
Conclusion
Variable lifetime is determined by scope: local variables live only during function execution, while global variables persist until the page is closed. Understanding lifetime helps prevent memory leaks and scope-related bugs.
