HomeJAVASCRIPTWhat is the difference between function declarations and function expressions?

What is the difference between function declarations and function expressions?

1. Function Declaration

  • A function declaration defines a named function using the function keyword.
  • It is hoisted completely, meaning you can call the function before it is defined in the code.

✅ Example:

sayHello(); // ✅ Works due to hoisting

function sayHello() {
  console.log("Hello from declaration!");
}

2. Function Expression

  • A function expression assigns a function (anonymous or named) to a variable.
  • Only the variable declaration is hoisted, not the function definition.
  • That means you cannot call it before defining it.

✅ Example:

sayHi(); // ❌ Error: Cannot access 'sayHi' before initialization

const sayHi = function () {
  console.log("Hello from expression!");
};

3. Key Differences

FeatureFunction DeclarationFunction Expression
HoistingFully hoisted (can be called before definition)Only variable is hoisted (function not available before definition)
Syntaxfunction name() {}const name = function() {}
Use caseWhen you want functions available throughout scopeWhen you want functions conditionally, inline, or assigned
Anonymous functionsNot possible (always needs a name)Possible (can be anonymous or named)

👉 In short:

  • Declarations → Hoisted, global availability.
  • Expressions → Not hoisted (only the variable is), often used in callbacks or assigned to variables.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *