JavaScript Scope
Scope defines where a variable can be accessed in your code.
In JavaScript, there are three main types of scope:
1. Global Scope
- Variables declared outside any function or block.
- Accessible everywhere in your code.
- Can cause naming conflicts if used carelessly.
Example:
var globalVar = "I'm global";
function test() {
console.log(globalVar); // I'm global
}
test();
console.log(globalVar); // I'm global
2. Local (Function) Scope
- Variables declared inside a function (
var
,let
, orconst
). - Accessible only within that function.
- Not visible outside the function.
Example:
function myFunction() {
var localVar = "I'm local";
console.log(localVar); // I'm local
}
myFunction();
// console.log(localVar); Error: localVar is not defined
3. Block Scope
- Introduced in ES6 with
let
andconst
. - Variables declared inside a block
{}
(like inif
,for
, orwhile
) are limited to that block. var
does not follow block scope, which can cause unintended behavior.
Example:
if (true) {
let blockVar = "I'm block-scoped";
var varVar = "I'm not block-scoped";
console.log(blockVar); // I'm block-scoped
}
// console.log(blockVar); Error: blockVar is not defined
console.log(varVar); // I'm not block-scoped (leaks out)
Summary
Scope Type | Declared With | Accessible Where | Notes |
---|---|---|---|
Global | var , let , const (outside functions/blocks) | Everywhere | Can cause conflicts |
Local (Function) | var , let , const (inside functions) | Inside the function | Isolated from outside |
Block | let , const | Inside {} only | Safer and modern practice |