Skip to content

Commit 041afed

Browse files
feat: add hoisting.js
1 parent 6de23c5 commit 041afed

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

part1 (Basics)/13_hoisting.js

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,43 @@
1-
getName();
2-
// JavaScript
1+
// hoisting.js
32

4-
console.log(x);
5-
// undefined
3+
// INFO: Hoisting in JavaScript
64

5+
/*
6+
Hoisting is a JavaScript mechanism where variables and function declarations
7+
are moved to the top of their scope (memory phase) before code execution.
8+
9+
Important:
10+
- Only **declarations** are hoisted, not **initializations**.
11+
- Function declarations are fully hoisted.
12+
- var is hoisted and initialized as undefined.
13+
- let and const are hoisted but not initialized (temporal dead zone).
14+
*/
15+
16+
// Function call before it's defined – this works because function declarations are hoisted
17+
getName(); // Output: "JavaScript"
18+
19+
// Accessing a 'var' variable before declaration – it's hoisted with undefined
20+
console.log(x); // Output: undefined
21+
22+
// Accessing the function by name – shows the function definition
723
console.log(getName);
8-
// function getName() {}
24+
// Output: [Function: getName]
925

1026
var x = 7;
1127

28+
// Function Declaration
1229
function getName() {
1330
console.log("JavaScript");
1431
}
32+
33+
/*
34+
Summary:
35+
36+
- Function declarations are hoisted completely (both name and body).
37+
- var is hoisted and set to undefined.
38+
- let and const are hoisted but in the "temporal dead zone" – accessing them before declaration causes ReferenceError.
39+
40+
Good Practice:
41+
- Always declare variables and functions at the top of their scope.
42+
- Prefer let and const over var to avoid confusion caused by hoisting.
43+
*/

0 commit comments

Comments
 (0)