Skip to content

Scope

Scope defines where a variable is accessible in your program.
In JavaScript, there are three main types of scope:

  1. Global: accessible everywhere.
  2. Function: accessible only inside a function.
  3. Block: accessible only inside a block { } (if, for, while…).

A variable declared outside any function or block is said to be global.
It is accessible from anywhere in the program.

let globalVariable = "I am global";
function showGlobal() {
console.log(globalVariable);
}
showGlobal(); // I am global
Warning

Too many global variables = hard to maintain code.


A variable declared inside a function only exists in that function.
We say it has a local scope.

function test() {
let localVariable = "Inside the function";
console.log(localVariable);
}
test();
// console.log(localVariable); // Error: not defined

With let and const, variables are limited to the block of code in which they are defined.

if (true) {
let blockVariable = "Inside the block";
console.log(blockVariable); // OK
}
// console.log(blockVariable); // Error: not defined

With var, this is not the case → var ignores block scope and behaves like a function-scoped variable.

if (true) {
var test = "I escape the block";
}
console.log(test); // "I escape the block"

Scope typeKeywords involvedAccessible where?
Globalvar, let, constEverywhere in the code (⚠️ avoid too many globals)
Functionvar, let, constOnly inside the function
Blocklet, constOnly inside the block { } (if, for, while…)

  • Use const by default, and let if the value must change.
  • Avoid var (old behavior, source of bugs).
  • Minimize global variables → prefer local variables and functions to better organize your code.