Function Hoisting
MediumIn plain terms
Function declarations are hoisted - they can be called before they appear in the code. Function expressions and arrow functions are not hoisted. Variable declarations are hoisted but not initializations.
What you need to know
- •Declarations hoisted
- •Expressions not hoisted
- •var vs let/const
Try it yourself
Copy the code below and run it in your browser console or a code editor:
// Works - declaration hoisted
sayHi();
function sayHi() {
console.log('Hi');
}
// Error - expression not hoisted
// sayHello();
const sayHello = function() { console.log('Hello'); };
// var is hoisted (undefined), let/const in TDZ
console.log(x); // undefined (var)
var x = 5;
// console.log(y); // Error - TDZ
let y = 10;Learn more
Dive deeper with these trusted resources: