Scope determines the accessibility of variables, functions, and objects in different parts of your code. In JavaScript, scope can be global, function, block, or module level.
1.1 Types of Scope
1.1.1 Global Scope
-
Variables declared outside any function or block have global scope.
-
Accessible from anywhere in the code.
1.1.2 Function Scope
-
Variables declared inside a function using
varare function-scoped. -
Only accessible inside the function.
1.1.3 Block Scope
-
Variables declared with
letorconstinside{}are block-scoped. -
Only accessible inside that block.
1.1.4 Lexical Scope
-
Scope determined by where functions are declared, not where they are called.
2. Hoisting in JavaScript
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution.
-
Only declarations are hoisted, not initializations.
-
varvariables andfunctiondeclarations are hoisted. -
letandconstare hoisted but are in the Temporal Dead Zone (TDZ) until they are initialized.
2.1 Hoisting with var
-
Explanation:
var a;is hoisted to the top, buta = 5remains in place.
2.2 Hoisting with let and const
-
Variables are in TDZ from the start of the block until initialized.
2.3 Hoisting with functions
Function Declaration
-
Fully hoisted (can be called before declaration):
Function Expression
-
If assigned to
var, only variable declaration is hoisted, not the function:
-
If assigned to
letorconst, it behaves like block-scoped variable in TDZ.
3. Scope and Hoisting Together
-
var: function-scoped, hoisted → accessible before initialization (undefined).
-
let / const: block-scoped, hoisted → not accessible before initialization (TDZ).
-
functions: declaration hoisted → can be called before definition.
4. Key Points
-
Hoisting moves declarations, not initializations.
-
var→ function scope, initialized asundefined. -
letandconst→ block scope, in TDZ until defined. -
Function declarations → fully hoisted.
-
Function expressions → only the variable is hoisted (not the function body).
-
Scope determines where variables and functions are accessible.
-
Lexical scope is resolved at compile time, not runtime
Comments
Post a Comment