47. Scope 101: Global vs. Local
Scope defines where variables and functions are accessible within your code. Understanding scope prevents naming conflicts and helps manage memory.
1. Global Scope
Variables declared outside of any function or block are in the global scope. They can be accessed from anywhere in the program.
javascript const applicationName = 'AppX'; // Global variable
function displayTitle() { // Can access global variable console.log(applicationName); }
displayTitle(); console.log(applicationName);
2. Local Scope (Function Scope)
Variables declared inside a function are in local scope (function scope) and are only accessible within that function.
javascript function calculate() { const localResult = 100; console.log(localResult); // OK }
calculate();
// console.log(localResult); // ERROR: ReferenceError, localResult is out of scope.
Note: This lesson primarily addresses var and function declarations. Lessons 8 and 9 introduced block scope (let/const), which we will consolidate next.