</> Code Corner

JavaScript · JS Tutorial · Lesson 38

JS Hoisting

Declarations are moved to the top.

Hoisting is JavaScript's default behaviour of moving declarations to the top of the current scope.

Example

<p id="demo"></p>
<script>
let out = "";
out += "Function called before it is declared: " + greet() + "<br>";
function greet() { return "Hi!"; }

out += "var before declaration: " + y + "<br>";   // undefined, not an error
var y = 7;

try {
  out += z;
  let z = 1;
} catch (e) {
  out += "let before declaration: " + e.name;
}
document.getElementById("demo").innerHTML = out;
</script>
  • Function declarations are fully hoisted
  • var declarations are hoisted, but not their values (they are undefined)
  • let and const are hoisted but not initialized — using them early throws a ReferenceError (the "temporal dead zone")

Keep reading “JS Hoisting”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋