Mark As Completed Discussion

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.

JAVASCRIPT
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.

JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment