Function Expression vs Function Declaration

 

JavaScript gives you two main ways to define functions: Function Declaration and Function Expression. Think of them like ordering coffee —one is like brewing it at home (declaration), and the other is like grabbing one from a café (expression). Both get the job done, but they have some key differences!

1. Function Declaration

A function declaration is a traditional way of defining a function. It’s straightforward and gets hoisted, meaning JavaScript knows about it before executing the code.

Example:

function sayHello() {
  console.log("Hello, world!");
}
sayHello();

Output:

Hello, world! 

Real-life analogy: Like writing down a to-do list in the morning. You plan ahead, and when the time comes, you execute it. 

2. Function Expression 

A function expression involves assigning a function to a variable. Unlike declarations, function expressions are not hoisted, meaning you can’t use them before they are defined.

Example:

const sayHello = function() {
  console.log("Hello, world!");
};
sayHello();

Output:

Hello, world! 

Real-life analogy: Like deciding to grab coffee when you’re already outside. You don’t plan ahead—you just do it when needed. 

3. Hoisting: The Big Difference 

Feature Function Declaration Function Expression
Hoisting Yes No
Can be used before definition? Yes No
Stored in a variable? No Yes

Example:

sayHello(); // Works fine
function sayHello() {
  console.log("Hello, hoisting!");
}

Output:

Hello, hoisting!

But with function expressions:

sayHello(); // ERROR! Cannot access before initialization
const sayHello = function() {
  console.log("Hello!");
};

4. Anonymous vs Named Function Expressions 

Function expressions can be anonymous (without a name) or named (with a name).

Example:

const anonymousFunc = function() {
  console.log("I have no name!");
};

const namedFunc = function hello() {
  console.log("I have a name!");
};

Real-life analogy: Anonymous functions are like mystery calls, while named functions are like saved contacts.

5. When to Use What?

  • Use function declarations when you need to call a function anywhere in your code (e.g., utility functions).
  • Use function expressions when defining functions dynamically (e.g., inside event listeners or callbacks).

Conclusion

Both function declarations and expressions are powerful, but understanding their differences helps you write better JavaScript!

Post a Comment

0 Comments