nameit finds it in its own scope.
For:
cityJavaScript looks in the outer scope.
For:
countryit goes one level further outward.
Conceptually:
inner scope
↓
outer scope
↓
global/module scope
This is the scope chain.
8️⃣ What Is Hoisting?
Hoisting describes how JavaScript's execution process makes certain declarations available before their position in the source code is reached.
But different declarations behave differently.
This is why you should avoid thinking of hoisting as simply:
"JavaScript moves all code to the top."
That's not an accurate mental model.
9️⃣ Function Declaration Hoisting
Function declarations can be called before their declaration in the same scope.
greet();
function greet() {
console.log("Hello");
}
Output:
Hello
The function declaration is available when execution begins.
🔟 "var" Hoisting
Consider:
console.log(age);
var age = 25;
The result is:
undefined
Conceptually, you can think of the declaration being initialized early:
var age;
console.log(age);
age = 25;
The important point is:
var declaration → initialized as undefinedbefore normal execution reaches the assignment.
1️⃣1️⃣ "let" and "const" Hoisting
Now consider:
console.log(age);
let age = 25;
This produces a
ReferenceError.The same applies to:
console.log(age);
const age = 25;
Why?
"let" and "const" declarations are created during the setup phase, but they aren't initialized until execution reaches their declaration.
The period between entering the scope and initialization is called the:
Temporal Dead Zone (TDZ)
1️⃣2️⃣ Temporal Dead Zone
Example:
{
console.log(name);
let name = "Rahul";
}The variable "name" exists in the scope, but accessing it before initialization causes an error.
Conceptually:
Block begins
↓
name exists but is uninitialized
↓
Temporal Dead Zone
↓
let name = "Rahul"
↓
name becomes initialized
So:
console.log(name);
let name = "Rahul";
is not equivalent to using "var".
1️⃣3️⃣ Why "let" and "const" Are Safer
Compare:
console.log(value);
var value = 10;
Output:
undefined
versus:
console.log(value);
let value = 10;
Error:
ReferenceError
The error makes the problem much easier to detect instead of silently giving you
undefined.1️⃣4️⃣ Function Scope vs Block Scope Example
Consider:
function test() {
if (true) {
let a = 10;
var b = 20;
}
console.log(b);
}
test();This works because "b" is function-scoped.
But:
function test() {
if (true) {
let a = 10;
}
console.log(a);
}