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
How to define global variable in a JavaScript function?
In JavaScript, you can define global variables either at global scope or from within functions using the window object. Here are the main approaches.
Method 1: Declaring at Global Scope
The most straightforward way is to declare variables outside any function at global scope:
<script>
var myGlobalVariable = "I'm global!";
function display() {
console.log(myGlobalVariable); // Accessible here
}
display();
console.log(myGlobalVariable); // Also accessible here
</script>
I'm global! I'm global!
Method 2: Using window Object Inside Functions
You can create global variables from within functions by assigning to the window object:
<script>
function createGlobal() {
window.myGlobalVar = "Created inside function";
}
createGlobal();
console.log(myGlobalVar); // Accessible globally
console.log(window.myGlobalVar); // Same variable
</script>
Created inside function Created inside function
Method 3: Omitting var/let/const (Not Recommended)
Variables declared without var, let, or const become global, but this is not recommended:
<script>
function createImplicitGlobal() {
implicitGlobal = "Accidentally global"; // No var/let/const
}
createImplicitGlobal();
console.log(implicitGlobal); // Works but not recommended
</script>
Accidentally global
Comparison
| Method | Best Practice? | Use Case |
|---|---|---|
| Global scope declaration | Yes | When you know you need a global variable |
| window object | Sometimes | Creating globals conditionally inside functions |
| Implicit globals | No | Avoid - causes bugs and issues |
Key Points
Global variables are accessible from anywhere in your code but can lead to naming conflicts. Use them sparingly and prefer module patterns or proper scoping when possible.
Conclusion
Declare global variables at global scope for clarity, or use window object inside functions when needed. Avoid implicit globals to prevent bugs and maintain clean code.
