Spot the Scope Bug
Question
This code throws a ReferenceError. What is wrong?
Code
function calculate() {
let result = 42;
return result;
}
console.log(result);
Hint
result is declared inside the function, so it does not exist outside.
Explanation
The variable result is declared inside the function calculate(), so it is local to that function. It does not exist outside. The fix is to call the function and use its return value: console.log(calculate()) which prints 42. The function returns the value; the variable itself is not accessible.
Related Resources
Related Lessons
- Scope and Visibility
Learn about scope and variable visibility.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.