Function Declaration vs Function Expression in JavaScript


Introduction
JavaScript functions play a crucial role in writing clean, reusable, and modular code. However, there are two main ways to define functions: function declarations and function expressions. Understanding their differences helps in writing efficient and maintainable code.
What is Function
A function in JavaScript is a reusable block of code designed to perform a specific task. It allows you to write a piece of logic once and use it multiple times without repeating the same code. Functions help in making the code more organized, readable, and efficient.
Think of a function like a coffee machine.
You give input (water, coffee beans, and milk).
The machine processes it.
You get an output (a cup of coffee).
In JavaScript, a function works similarly:
You pass data (input).
The function executes a set of instructions.
It returns a result (output).
JavaScript Example (Coffee Machine Function)
// Function to make coffee
function makeCoffee(sugar, milk) {
return `Your coffee with ${sugar} spoons of sugar and ${milk}ml of milk is ready!`;
}
// Calling the function
let myCoffee = makeCoffee(2, 100);
console.log(myCoffee);
Function Definition:
makeCoffee(sugar, milk)
– takes two inputs (sugar & milk).Processing: Creates a message based on the given inputs.
Return Value: Sends back the message.
Function Call:
makeCoffee(2, 100)
– provides specific values (2 spoons of sugar, 100ml milk).Output: Displays:
"Your coffee with 2 spoons of sugar and 100ml of milk is ready!"
Why Functions Are Important?
Reusability: Write once, use multiple times.
Modularity: Break down complex code into smaller, manageable parts.
Maintainability: Easier to update and debug.
Abstraction: Hide implementation details and expose only necessary functionality.
1. Function Declaration
Real-World Example
Think of a restaurant menu:
The menu (function declaration) is written before customers arrive.
When a customer orders a dish, the restaurant knows how to prepare it because the recipe (function) was already declared.
The dish is served (function executes and returns the result).
JavaScript Example (Restaurant Order Function)
// Function declaration
function orderFood(dish) {
return `Your ${dish} is being prepared!`;
}
// Calling the function
console.log(orderFood("Pizza"));
console.log(orderFood("Burger"));
Hoisting: Function declarations are hoisted to the top of their scope, so they can be called before their definition.
console.log(orderFood("Pizza")); // ✅ Works due to hoisting
// Function declaration
function orderFood(dish) {
return `Your ${dish} is being prepared!`;
}
// Calling the function
console.log(orderFood("Burger"));
Output:
Your Pizza is being prepared!
Your Burger is being prepared!
2.Function Expression
A function expression is a way to define a function and store it inside a variable. Unlike function declarations, function expressions are not hoisted, which means they can only be used after they are defined.
Real-World Example
Think of a food delivery app:
The app asks for your location before it shows available restaurants.
The function to fetch restaurants is stored in a variable and used only after you enter your location.
JavaScript Example (Food Delivery App)
// Function expression stored in a variable
const getRestaurants = function(location) {
return `Showing restaurants near ${location}`;
};
// Calling the function
console.log(getRestaurants("Delhi"));
console.log(getRestaurants("Mumbai"));
Function Expression: The function is assigned to
getRestaurants
.Calling the Function: Only after defining it, we call
getRestaurants("Delhi")
.Output:
Showing restaurants near Delhi
Showing restaurants near Mumbai
Real-World Use Cases of Function Declarations vs Function Expressions
1. When to Use Function Declarations
Function declarations are useful when defining reusable functions that need to be available throughout the code.
Example: Utility Functions in a Script
// Function declaration (Hoisted)
function calculateArea(width, height) {
return width * height;
}
console.log(calculateArea(5, 10)); // ✅ Output: 50
// You can call `calculateArea` anywhere in the script because of hoisting.
Why use function declarations here?
The function is needed throughout the script.
It improves readability and organization.
Hoisting ensures the function is available at the top of the script.
2. When to Use Function Expressions
Function expressions are useful for callbacks, event handlers, and storing functions in variables.
Example 1: Callback Function in an Event Listener
document.getElementById("btn").addEventListener("click", function () {
console.log("Button Clicked!");
});
Why use a function expression here?
The function doesn’t need to be reused elsewhere.
It’s an anonymous function (no need for a name).
It’s passed directly as a callback to
addEventListener()
.
Difference Between Function Declaration and Function Expression
Feature | Function Declaration | Function Expression |
Definition | A function that is declared using the function keyword with a name. | A function that is assigned to a variable |
Hoisting | yes - Can be called before it defined | No - Cannot be called before it is define |
Syntax | function funcName() {} | const funcName = function() {}; |
Usage | Used for defining reusable function that can be called anywhere. | Used when function need to be assigned to varriables or passed as argument. |
Function Name | Always has a name | Can be anonymous(without a name) or named. |
Best Use Case | When you need a function that can be used anywhere in the script. | When you need a function for a specific scope, like inside a variable or callback. |
Conclusion
Understanding the difference between function declarations and function expressions helps you write cleaner and more predictable JavaScript code. Function declarations are hoisted, making them accessible anywhere in the script, while function expressions provide more control over function usage.
Subscribe to my newsletter
Read articles from Kajal jaiswal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
