Clean β’ Professional
Scope defines where a variable can be accessed in your code.
In JavaScript, there are three main types of scope:

Example:
var globalVar = "I'm global";
function test() {
console.log(globalVar); // I'm global
}
test();
console.log(globalVar); // I'm global
var, let, or const).Example:
function myFunction() {
var localVar = "I'm local";
console.log(localVar); // I'm local
}
myFunction();
// console.log(localVar); Error: localVar is not defined
let and const.{} (like in if, for, or while) 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)
| 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 |