Course contentsShow
← JavaScript
Lesson 75 of 2,7233. Variables and ScopeFree lesson

Undeclared Variables and Implicit Globals

Discover the dangers of assigning to undeclared variables and how strict mode prevents it.

Undeclared Variables and Implicit Globals

What you'll learn: How accidentally skipping variable declarations creates dangerous global variables.

The Hidden Danger

When you assign a value to a name that hasn't been declared with var, let, or const, JavaScript doesn't throw an error in normal mode—it silently creates a global variable. This is called an "implicit global" and it's one of JavaScript's most notorious pitfalls.

function setName() {
  userName = "Alice";  // No var, let, or const!
}

setName();
console.log(userName);  // "Alice" — accessible globally!

Even though userName was assigned inside a function, it became a property of the global object because we forgot to declare it. This can lead to unexpected bugs when different parts of your code accidentally share the same variable name.

Why This Is Dangerous

Imagine multiple functions all accidentally using the same undeclared variable name. They'd silently overwrite each other's data, creating bugs that are extremely hard to track down.

Think of it like this: Declaring a variable is like labeling your lunch in the office fridge. An undeclared variable is like leaving unlabeled food—anyone can take it, and chaos ensues when everyone assumes it's theirs.

The Solution: Strict Mode

JavaScript's strict mode catches this mistake and throws an error:

"use strict";

function setAge() {
  age = 25;  // ReferenceError: age is not defined
}

Always use strict mode and always declare your variables with let or const.

Key Takeaway: Assigning to an undeclared variable creates an implicit global, which causes hard-to-debug errors. Always declare variables with let or const, and use "use strict"; to catch these mistakes.