Skip to main content

Command Palette

Search for a command to run...

Function Declaration vs Function Expression: What’s the Difference?

Published
3 min read
Function Declaration vs Function Expression: What’s the Difference?

In programming, a function is a reusable block of code. Think of it like a "mini-machine": you build it once, and then you can press a button to run it whenever you need to perform a specific task, like calculating a sum or formatting a user's name.

Topics that we are going to discuss in this blog are as follows.

  • Why Do We Need Functions?

  • Function Declaration

  • Function Expression

  • Key differences between declaration and expression

  • Basic idea of hoisting (very high level)

  • When to use each type


Why Do We Need Functions?

Imagine you need to multiply two numbers in ten different places in your code. Instead of writing a * b ten times, you write a function once. If you ever need to change how that calculation works (e.g., adding tax), you only change it in one-place.


Function Declaration (The Standard Way)

A Function Declaration is the most common way to define a function. You use the function keyword, give it a name, and define its logic.

// Function Declaration
function multiply(a, b) {
  return a * b;
}

console.log(multiply(5, 4)); // Output: 20

Function Expression (The Variable Way)

A Function Expression is when you create a function and assign it to a variable. In this case, the function is often "anonymous" (it doesn't have its own name) because the variable name is used to call it.

// Function Expression
const multiplyExpr = function(a, b) {
  return a * b;
};

console.log(multiplyExpr(5, 4)); // Output: 20

The "Hoisting" Difference (High Level)

This is where things get interesting. In JavaScript, Hoisting is a behavior where the engine moves declarations to the top of the code before running it.

  • Declarations are hoisted: You can call a function before you even define it in your code.

  • Expressions are NOT hoisted: If you try to call a function expression before it’s defined, your code will crash.

// This works! (Hoisted)
sayHello(); 
function sayHello() {
  console.log("Hello from the declaration!");
}

// This crashes! (Not hoisted)
sayHi(); 
const sayHi = function() {
  console.log("Hi from the expression!");
};

When to Use Which?

  • Use Declarations when you want a function to be available everywhere in your script or for general utility functions.

  • Use Expressions when you want to keep your code organized, limit where a function can be accessed, or when you’re passing functions into other methods (like map or filter).


Conclusion

Whether you prefer the traditional declaration or the modern expression, the goal is the same: reusability. By moving your logic into functions, you make your code more organized and much easier to debug. Checkout the cover image to brush up this blog.