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 happens when you do not declare a variable in JavaScript?
When you don't declare a variable in JavaScript using var, let, or const, JavaScript automatically creates it as a global variable. This behavior can lead to unexpected results and is generally considered bad practice.
How Undeclared Variables Work
When you assign a value to an undeclared variable, JavaScript creates it in the global scope, even if you're inside a function. This happens because JavaScript searches the scope chain for the variable, and if not found, creates it globally.
Example: Undeclared vs Declared Variables
<html>
<body>
<script>
var rank = 5;
points = 50; // Undeclared - becomes global
marks = 300; // Undeclared - becomes global
// Anonymous function
(function() {
points = 100; // Overwrites global points
var rank = 4; // Creates new local variable
var marks = 900; // Creates new local variable
document.write("Inside function:<br/>");
document.write("rank: " + rank + "<br/>"); // prints 4
document.write("points: " + points + "<br/>"); // prints 100
document.write("marks: " + marks + "<br/>"); // prints 900
})();
document.write("<br/>Outside function:<br/>");
document.write("rank: " + rank + "<br/>"); // prints 5
document.write("points: " + points + "<br/>"); // prints 100 (changed!)
document.write("marks: " + marks + "<br/>"); // prints 300
</script>
</body>
</html>
Output
Inside function: rank: 4 points: 100 marks: 900 Outside function: rank: 5 points: 100 marks: 300
Key Differences
| Variable | Declaration | Scope | Behavior |
|---|---|---|---|
rank |
Declared with var
|
Function-scoped | Creates new variable in function |
points |
Undeclared | Global | Modifies global variable |
marks |
Mixed (global undeclared, local declared) | Both global and local | Creates separate local variable |
Problems with Undeclared Variables
Undeclared variables can cause several issues:
- Unintended global pollution: Variables become global even when you meant them to be local
- Difficult debugging: Hard to track where variables are created and modified
-
Strict mode errors: Throws
ReferenceErrorin strict mode
Best Practices
Always declare variables explicitly:
<script>
// Good practices
var globalVar = "I'm global";
let blockScoped = "I'm block-scoped";
const constant = "I can't be reassigned";
function myFunction() {
var localVar = "I'm local to this function";
let anotherLocal = "I'm also local";
// Avoid this:
// undeclaredVar = "This becomes global accidentally";
}
</script>
Conclusion
Undeclared variables in JavaScript automatically become global, which can lead to bugs and unexpected behavior. Always use var, let, or const to explicitly declare variables and maintain proper scope control.
