Js Scope in JavaScript
? JavaScript Scope
Scope defines the accessibility or lifetime of variables and functions in your code. It determines where a variable can be accessed.
Types of Scope in JavaScript
1. Global Scope
Variables declared outside any function or block.
Accessible from anywhere in the code.
var globalVar = "I'm global";function test() { console.log(globalVar); // Accessible here}test();console.log(globalVar); // Accessible here too2. Function Scope
Variables declared inside a function using
varare scoped to that function.Not accessible outside the function.
function example() { var localVar = "I'm local"; console.log(localVar); // Works here}example();console.log(localVar); // Error: localVar is not defined3. Block Scope (ES6+)
Variables declared with
letorconstinside{}blocks (like insideif,for) are scoped to that block.
if (true) { let blockVar = "I'm block scoped"; const blockConst = 42; console.log(blockVar); // Accessible here}console.log(blockVar); // Error: blockVar is not definedconsole.log(blockConst); // Error: blockConst is not definedScope Chain
When accessing a variable, JavaScript looks in the current scope.
If not found, it looks in the outer scope, continuing up to the global scope.
If variable is not found anywhere, it's
undefinedor throws ReferenceError if accessed before declaration (forlet/const).
Example of Scope Chain
let a = "global";function outer() { let b = "outer"; function inner() { let c = "inner"; console.log(a); // global console.log(b); // outer console.log(c); // inner } inner();}outer();Summary
| Scope Type | Declared With | Accessible Where |
|---|---|---|
| Global | var, let, const outside functions | Everywhere |
| Function | var inside functions | Only inside the function |
| Block | let, const inside blocks | Only inside the block {} |
If you want, I can also explain hoisting and how it relates to scope!