Course contentsShow
← JavaScript
Lesson 422 of 2,72311. FunctionsFree lesson

Function Declaration Hoisting

Discover how function declarations are hoisted to the top of their scope before code execution.

Function Declaration Hoisting

You'll learn how JavaScript moves function declarations to the top of their scope before running any code.

What Is Hoisting?

JavaScript has a unique behavior: before executing your code line-by-line, it first scans for function declarations and "hoists" them to the top of their scope. This means you can call a function before it appears in your code, and it will still work.

Think of it like a teacher preparing a classroom before students arrive. Before the lesson starts (code execution), the teacher places all the tools (function declarations) where they're needed, even if those tools were originally listed at the bottom of the supply list.

How It Works

greet(); // This works! Outputs: "Hello!"

function greet() {
  console.log("Hello!");
}

Even though greet() is called before its declaration, JavaScript has already "hoisted" the entire function definition to the top of the scope during the compilation phase. The code effectively runs as if it were written:

function greet() {
  console.log("Hello!");
}

greet(); // Outputs: "Hello!"

Only Declarations Are Hoisted

This hoisting behavior only applies to function declarations, not function expressions:

sayHi(); // Error! Cannot access before initialization

const sayHi = function() {
  console.log("Hi!");
};

Function expressions (like the one above) follow normal variable hoisting rules, meaning only the variable declaration is hoisted, not its assignment.

Key Takeaway: Function declarations are fully hoisted to the top of their scope, allowing you to call them anywhere in that scope, even before they appear in your code.