Scope
The current context of execution in JavaScript that determines the accessibility of variables, objects, and functions in your code.
Overview
Scope defines where variables and functions are accessible in your code. JavaScript has function scope, block scope (with let and const), and global scope. Understanding scope is essential for writing clean code, avoiding bugs, and managing variable lifecycles effectively.
Example
javascript// Global scope const globalVar = 'I am global'; function outerFunction() { // Function scope const outerVar = 'I am outer'; function innerFunction() { // Inner function scope const innerVar = 'I am inner'; console.log(globalVar); // Accessible console.log(outerVar); // Accessible console.log(innerVar); // Accessible } console.log(innerVar); // Error: not accessible } // Block scope with let/const if (true) { let blockVar = 'block scoped'; var functionVar = 'function scoped'; } console.log(functionVar); // Accessible console.log(blockVar); // Error: not accessible
Key Points
- Three types: global, function, and block scope
- let and const are block-scoped
- var is function-scoped
- Inner scopes can access outer scopes
- Outer scopes cannot access inner scopes
Learn More
- Closure - Closures
- Hoisting - Variable hoisting
- MDN: Scope