File tree Expand file tree Collapse file tree 1 file changed +34
-5
lines changed
Expand file tree Collapse file tree 1 file changed +34
-5
lines changed Original file line number Diff line number Diff line change 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
723console . log ( getName ) ;
8- // function getName() {}
24+ // Output: [Function: getName]
925
1026var x = 7 ;
1127
28+ // Function Declaration
1229function 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+ */
You can’t perform that action at this time.
0 commit comments