Hoisting
Learn how var and function declarations are hoisted while let/const are not.
What is hoisting?
Hoisting is the JavaScript engine treating some declarations as if they were moved to the top before the code runs. Variables declared with var and function declarations are hoisted; they can be used before their definition.
But let and const are not hoisted. If you access them before the definition you get a ReferenceError; this is called the temporal dead zone (TDZ). That is why in modern code it is safest to keep declarations at the top of the file or function.
Function hoisting
A function declaration is hoisted together with its whole body. So even if you define function greet() { return 'hello'; } at the end of the file, a greet() call above it works.
But a function expression does not work this way. When you write const greet = function() { ... };, only the greet variable is declared; the function itself cannot be called until the assignment runs. You will see this difference often in old code.
Exercise Show function hoisting
Write the function start() definition at the bottom of the code. The function should return "started". At the top, log the result with console.log(start()). Thanks to hoisting, calling it before the definition works.
Show example solution
console.log(start());
function start() {
return "started";
}
Test yourself
-
What does this code print?
console.log(greet()); function greet() { return 'hello'; }- hello
- undefined
- ReferenceError
- TypeError
Show answer
hello — Correct. The function declaration is hoisted, so it can be called before its definition.
-
Which keyword makes this code run without error?
console.log(city); ____ city = 'Istanbul';Show answer
console.log(city); var city = 'Istanbul'; -
Match the declaration to its behavior
- var x = 1
- Hoisted
- let x = 1
- TDZ, not accessible early
- const x = 1
- TDZ, cannot reassign
- function f() {}
- Hoisted with body