Quick Answer
Resolve ReferenceError when using undefined variables.
Understanding the Issue
This error occurs when trying to access a variable that hasn't been declared in the current scope. In strict mode, this also occurs for undeclared variables that would otherwise become global properties.
The Problem
This code demonstrates the issue:
Javascript
Error
console.log(x); // x was never declared
function example() {
console.log(y); // y not defined in this scope
}
The Solution
Here's the corrected code:
Javascript
Fixed
// Solution 1: Declare before use
const x = 5;
console.log(x);
// Solution 2: Proper scoping
function example() {
const y = 10;
console.log(y);
}
// Solution 3: Check typeof
if (typeof z !== 'undefined') {
console.log(z);
}
Key Takeaways
Always declare variables before use and understand JavaScript scoping rules.