Decoding the Enigma of Hoisting
The Concept of Hoisting
Hoisting is a feature in JavaScript that often perplexes newcomers. Simply put, hoisting allows variables and function declarations to be moved to the top of their containing scope during the compilation phase. This makes these variables and functions accessible even before the code executes.
The Inner Workings of the JavaScript Engine
The JavaScript engine performs a "pre-scan" of the code and hoists—or moves up—the declarations. This is why you can access variables even before they appear to be initialized.
1console.log(myVar); // Output: undefined
2var myVar = 10;
Understanding undefined
When a variable is hoisted, JavaScript automatically assigns it an initial value of undefined
. It remains undefined
until it's explicitly initialized.
1var name;
2console.log(name); // Output: undefined
3name = "Alice";
4console.log(name); // Output: Alice
The Catch
While hoisting allows you to use variables before their declarations, it doesn't mean they'll have the values you expect. As seen in the example above, hoisted variables start off as undefined
.
xxxxxxxxxx
console.log('name is ', name); // Undefined
var name = "Susan";
console.log('name is ', name); // Susan