Scope in JavaScript
Scope is where values and expressions are available for use. Think of scopes as a pyramid: child scopes can access 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 move to the top of their containing scope during compilation. So they can be used before they appear in the code.
Because of hoisting, blocks scope let and const but not var. Declare a variable with var inside a block and it's hoisted to the containing function or global scope, not the block.
This is a key reason modern JavaScript prefers let and const over var.
Quick Recap
-
Scope Types
- Global scope: Accessible everywhere
- Function scope: Limited to function boundaries
- Block scope: Limited to block boundaries
-
Variable Declaration
vardeclarations are function-scopedletandconstare block-scoped- Block scope only affects
letandconst vardeclarations are affected by hoisting
-
Best Practices
- Use
constby default - Use
letwhen reassignment is needed - Avoid
varin modern JavaScript - Be mindful of scope boundaries
- Use