๐ก Scope, Hoisting & Execution Context
Now we're moving from basic JavaScript syntax into concepts that explain how JavaScript actually executes your code.
These concepts are extremely important because they explain things like:
โข Why some variables are accessible in certain places but not others
โข Why functions can sometimes be called before they are written
โข Why "let" and "const" behave differently from "var"
โข How JavaScript manages function calls
โข How nested functions access variables from outer functions
1๏ธโฃ What Is Scope?
Scope determines where a variable can be accessed in your program.
For example:
let name = "Rahul";
console.log(name);
The variable "name" is accessible here because it was declared in the outer scope.
But:
function greet() {
let message = "Hello";
console.log(message);
}
greet();"message" is available inside "greet()".
Trying to access it outside:
console.log(message);
causes an error because "message" belongs to the function's local scope.
2๏ธโฃ Global Scope
A variable declared outside functions and blocks is generally in the global/module scope depending on how your JavaScript is executed.
Example:
const appName = "My App";
function showAppName() {
console.log(appName);
}
showAppName();
Output:
My App
The function can access "appName" because the variable exists in an outer scope.
3๏ธโฃ Function Scope
Variables declared inside a function are accessible within that function.
function calculate() {
const price = 1000;
console.log(price);
}
calculate();This works.
But:
console.log(price);
doesn't work because "price" exists only inside "calculate()".
4๏ธโฃ Block Scope
A block is code surrounded by "{}".
For example:
if (true) {
let message = "Hello";
console.log(message);
}"message" exists inside that block.
But:
console.log(message);
causes an error.
Variables declared using:
โข let
โข const
are block-scoped.
5๏ธโฃ "var" and Block Scope
This is one reason "var" can cause confusing behavior.
if (true) {
var message = "Hello";
}
console.log(message);This can print:
Hello
because "var" is not block-scoped.
Compare:
if (true) {
let message = "Hello";
}
console.log(message);This causes an error because "let" is block-scoped.
Remember:
โข var โ function-scoped
โข let โ block-scoped
โข const โ block-scoped
6๏ธโฃ Lexical Scope
JavaScript uses lexical scoping.
This means the scope of a variable is determined by where the code is written, not where the function is eventually called.
Example:
const name = "Rahul";
function outer() {
function inner() {
console.log(name);
}
inner();
}
outer();
"inner()" can access "name" because "name" exists in an outer lexical scope.
7๏ธโฃ Scope Chain
What happens if JavaScript can't find a variable in the current scope?
It looks outward.
Example:
const country = "India";
function outer() {
const city = "Pune";
function inner() {
const name = "Rahul";
console.log(name);
console.log(city);
console.log(country);
}
inner();
}
outer();