Scope in JavaScript
The scope is where values and expressions are available for use. Scopes can be treated as a pyramid where child scopes have access to parent scopes.
JavaScript has 3 types of scope:
- Global scope
- Function scope
- Block scope
Global Scope
The scope that contains and is accessible in all other scopes
Function Scope
The scope created with a function
Variables created inside a function scope cannot be accessed from outside the function
Block Scope
The scope created with a pair of curly braces
Variables created inside a block scope cannot be accessed from outside the block
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. This means they can be used before they appear in the code.
Blocks only scope let
and const
declarations, but not var
declarations due to hoisting. When you declare a variable with var
inside a block, it's actually hoisted to the function or global scope that contains it, not the block scope.
This is one of the key reasons why modern JavaScript recommends using let
and const
over var
.
Key Takeaways
-
Scope Types
- Global scope: Accessible everywhere
- Function scope: Limited to function boundaries
- Block scope: Limited to block boundaries
-
Variable Declaration
var
declarations are function-scopedlet
andconst
are block-scoped- Block scope only affects
let
andconst
var
declarations are affected by hoisting
-
Best Practices
- Use
const
by default - Use
let
when reassignment is needed - Avoid
var
in modern JavaScript - Be mindful of scope boundaries
- Use
References
Let's work together
I build exceptional and accessible digital experiences for the web
WRITE AN EMAILor reach out directly at hello@mohammadshehadeh.com