JavaScript: Hoisting
A simple question about hoisting in javascript, with a code example question
Definition of hoist … 1 : lift, raise especially : to raise into position
Hoisting is a JavaScript feature where variables and function declarations are moved to the top of their scope. This means where they are defined in the code isn’t as important as in other languages.
JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script. The JavaScript engine creates the global execution context before it starts to execute any code.
This happens even before the script is run! Wow, thank you JavaScript!
So what actually happens is, JavaScript will look for variables and add placeholders for all variables, but they will be undefined. Javascript will look for any functions and move them to the top as well.
The results of this:
- Regular functions regardless of where they are defined, will be accessible because of hoisting
- Variables on the other hand will show up as undefined, till they are defined
- Functions which are defined as variables, or arrow functions will also be undefined until they are defined
See the code snippet below:
console.log(x); // undefinedconsole.log(y); // error, y is not defined anywhere in the code, even later, so it is a reference errorvar x = 7;getName(); // calling the getName function before it’s definition is OK because of hoistingfunction getName() { console.log (“get Name function”)}console.log (x); // output 7getNameArrowFunction(); // undefined
// arrow functions act differently, they are treated like variablesvar getNameArrowFunction = () => { console.log (“get Name function: arrow version”)}getNameArrowFunction(); // This is OKgetNameVariableFunction(); // undefinedvar getNameVariableFunction = function nameDoesntMatter() { console.log (“get Name function: another version”)}