DEV Community

Cover image for Function Declaration vs Function Expression: What’s the Difference?
Ritam Saha
Ritam Saha

Posted on

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

Introduction

Hey there, my fellow code readers!

Imagine this: You're running a small family-owned kirana store in a busy Mumbai neighbourhood, where every day brings a flood of customers asking for the same things – calculating the total cost of groceries, applying a loyalty discount, or figuring out change for a ₹500 note. Instead of crunching the numbers from scratch each time, wouldn't it be smarter to have a quick, reusable method ready at hand? Like that well-worn ledger formula your dad uses to tally up daily sales without reinventing the wheel.

That's precisely what functions are in JavaScript – reusable blocks of code that handle repetitive tasks efficiently. Whether you're coding an app to manage inventory for your shop during festive seasons like Ganesh Chaturthi or building an online delivery system for essentials, grasping functions is essential. But here's the fun part: functions come in two main styles – declarations and expressions.

In this blog, we'll unpack them step by step, with examples as everyday as adding up items in a customer's basket at your local store. Let's get started!


What Are Functions and Why Do We Need Them?

Before learning about function declaration and function expression, we must need to know what is this function?! Why do we need them at all?

At their core, functions are like those family heirloom recipes passed down through generations in Indian households – reusable sets of instructions that perform a specific task.

In programming, especially in JavaScript, a function is a block of code designed to do something useful, like calculating the total runs scored by your favorite IPL team or figuring out the discount on a festive sale. Why do we need them? Well, imagine restocking shelves in your kirana store: You check the price of rice multiple times a day for different customers. Without functions, you'd rewrite the pricing logic every single time – tedious, error-prone, and a waste of effort.

Functions let you define the logic once and call it whenever needed, making your code cleaner, more efficient, and easier to maintain. They're the backbone of programming, just like how modular kitchens have revolutionized Indian homes by keeping everything organized and reusable.


Function Declaration Syntax:

A function declaration is the straightforward way to define a function. The syntax looks like this:

function functionName(parameters) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Here's a practical example: Let's say you're at a local market in Delhi, bargaining for spices. You want a function to multiply the price per kg by the quantity to get the total cost.

function multiplyNumbers(a, b) {
  return a * b;
}

console.log(multiplyNumbers(50, 3)); // Output: 150 (e.g., 3 kg of masala at ₹50/kg)
Enter fullscreen mode Exit fullscreen mode

This is a function declaration.
You define it with the function keyword, give it a name (multiplyNumbers), specify parameters (a and b), and include the code inside curly braces. Simple, right? It's like writing down your grandmother's recipe for aloo paratha – once declared, you can use it anytime.


Function Expression Syntax:

Now, a function expression is a bit more flexible. The syntax is:

const functionName = function(parameters) {
  // code to be executed
};
Enter fullscreen mode Exit fullscreen mode

Let's see with the same multiplication logic but now to calculate the price of pani puri plate.

const multiplyNumbersExpr = function(a, b) {
  return a * b;
};

console.log(multiplyNumbersExpr(20, 10)); // Output: 200 (e.g., 10 plates of pani puri at ₹20 each)
Enter fullscreen mode Exit fullscreen mode

Here, the function doesn't have a name by itself (it's anonymous), but we assign it to a variable (multiplyNumbersExpr). You can then call it using that variable. It's handy when you need a function as part of a larger expression, like passing it around in your code.


Basic Idea of Hoisting

Hoisting? Sounds fancy right?! but think of it like how in Indian trains, your reserved seat is "available" even if you board late – it's pulled up for you in advance.

In simple terms: JavaScript "hoists" (moves to the top of the scope logically) function declarations during compilation, so you can call them before they're defined in the code. Function expressions? Not so much – they're treated like variables, so calling them before definition throws an error. Internally during the creation phase of the local execution context, JavaScript stores the entire function declaration in memory with their full definition, but function expressions behave like variables and remain uninitialized until execution as they follow variable hoisting rules. For more details on hoisting, please read my previous blog which is on Hoisting and Temporal Dead Zone but after completing current one!

Let's observe with our examples:

First, the declaration:

console.log(multiplyNumbers(5, 4)); // Output: 20 (Works fine!)

function multiplyNumbers(a, b) {
  return a * b;
}
Enter fullscreen mode Exit fullscreen mode

It works because of hoisting – the function is "lifted" up logically.

Now, the expression:

console.log(multiplyNumbersExpr(5, 4)); // Error: Cannot access 'multiplyNumbersExpr' before initialization

const multiplyNumbersExpr = function(a, b) {
  return a * b;
};
Enter fullscreen mode Exit fullscreen mode

Boom! Error. No hoisting here, so it doesn't work before definition.

Declarations are ready from the start; Expressions need to be defined first.


Key Differences Between Declaration and Expression

To make this crystal clear, let's compare them side by side, just like weighing pros and cons before choosing between a traditional thali or a fusion meal.

Difference

Here's what the table highlights:

  • Syntax: Declaration starts with function keyword followed by name. Expression assigns a function to a variable.
  • Naming: Declarations must have a name. Expressions can be anonymous but should be assigned to a variable.
  • Hoisting: As we just explored, declarations are hoisted (available before definition), while expressions are not (must be defined before use).
  • Usage: Declarations are standalone. Expressions are used in variables or as arguments.
  • Readability: Declarations are more explicit, like a formal invitation. Expressions are concise, like a WhatsApp forward.

In essence, these differences boil down to how and when you want your functions to be accessible in your code – with declarations offering more upfront availability thanks to hoisting, and expressions providing greater flexibility in dynamic scenarios.


When to Use Each Type

So, now a question should arrive in your mind: when to pick one over the other?

  • Use Function Declarations when you want clarity and don't mind them being available everywhere in the scope. Great for main utility functions, like a reusable calculator for wedding budgets in a large joint family.
  • Use Function Expressions when you need flexibility, such as in callbacks (e.g., for event handlers in a festival app) or when assigning functions dynamically. They're perfect for modern, modular code. You can think of it like an wedding planner gets called whenever needed to plan wedding in a big joint family.

In practice, if hoisting matters (rarely an issue in well-structured code), go for declarations. Otherwise, expressions align with const/let best practices.


Wrapping It Up with a Quick Assignment

To adapt these home, try this yourself:

  • Write a function declaration to multiply two numbers (e.g., calculating total votes in a local election).
  • Rewrite it as a function expression.
  • Call both and print results.
  • Try calling before defining – see what happens!

Code Execution

This visual will show how a function call flows: From invocation to execution, highlighting where hoisting kicks in for declarations.

There you have it – functions demystified! Though there is also another type of function expression called as Arrow function, but we will discuss about that in detail in our upcoming blog. Whether you're coding for a startup in Bangalore or just tinkering with personal projects, mastering declarations vs. expressions will make your JavaScript journey as smooth as a butter naan. Got questions? Drop them in the comments!

Top comments (0)