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

Declaration vs Expression: Hoisting Behavior

Compare how function declarations are hoisted while expressions are not.

Declaration vs Expression: Hoisting Behavior

You'll learn why function declarations can be called before they appear in your code, while function expressions cannot.

The Core Difference

JavaScript "hoists" function declarations to the top of their scope during the compilation phase, making them available throughout the entire scope — even before the line where they're written. Function expressions, however, are not hoisted. They behave like regular variable assignments: you can only use them after the line where they're defined.

Think of it like this: function declarations are like celebrities at a party — everyone knows they're there from the moment they arrive (the scope begins). Function expressions are like regular guests who must introduce themselves first — you only know about them after you've met them (executed the assignment line).

How It Works

// This works! Function declaration is hoisted
greet(); // "Hello!"

function greet() {
  console.log("Hello!");
}
// This fails! Function expression is NOT hoisted
sayHi(); // Error: Cannot access 'sayHi' before initialization

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

With function expressions, the variable (sayHi) is hoisted, but it starts as undefined (for var) or in a "temporal dead zone" (for let/const). The actual function isn't assigned until that line executes.

Why This Matters

Understanding hoisting helps you:

  • Organize code logically (declarations can go after usage)
  • Avoid confusing errors with expressions
  • Choose the right style for your needs

Key Takeaway: Function declarations are fully hoisted and usable anywhere in their scope, while function expressions only become available after their assignment line executes.