Scope
What is Scope?
Section titled “What is Scope?”Scope defines where a variable is accessible in your program.
In JavaScript, there are three main types of scope:
- Global: accessible everywhere.
- Function: accessible only inside a function.
- Block: accessible only inside a block
{ }
(if, for, while…).
Global Scope
Section titled “Global Scope”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.
Function Scope
Section titled “Function Scope”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
Block Scope
Section titled “Block Scope”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 Summary
Section titled “Scope Summary”Scope type | Keywords involved | Accessible where? |
---|---|---|
Global | var , let , const | Everywhere in the code (⚠️ avoid too many globals) |
Function | var , let , const | Only inside the function |
Block | let , const | Only inside the block { } (if, for, while…) |
Best Practices
Section titled “Best Practices”- Use
const
by default, andlet
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.