π§ JavaScript Function Concepts: Function Declaration vs Function Expression

In JavaScript, functions are a key part of writing reusable, clean, and powerful code. But when we start learning functions, two common terms confuse many learners:
Function Declaration
Function Expression
Letβs understand both in detail with simple examples and real-life comparisons.
π 1. What is a Function?
Before jumping into the types, letβs recall what a function is.
A function in JavaScript is a block of code that performs a specific task.
You can use it again and again just by calling its name.
Real-life Example:
Think of a function like a coffee machine:
You press a button β coffee machine runs the process (function) β gives you coffee (output).
You can press the button again and again without writing new instructions.
β Function Declaration
π Definition:
A Function Declaration means you define a function using the function
keyword and give it a name.
function greetUser() {
console.log("Hello, welcome to our website!");
}
π How to use:
You can call this function by just using its name followed by ()
:
greetUser(); // Output: Hello, welcome to our website!
β Important Points:
Function declaration starts with the
function
keyword.It has a name (
greetUser
in this case).You can call this function even before you define it. (Because of hoisting β explained below)
π‘ Real-life Example (Function Declaration):
Imagine you are creating a web page for a travel website. You want to show a greeting message to users when they open the page:
function showWelcomeMessage() {
alert("Hi there! Ready to explore the world?");
}
showWelcomeMessage(); // Will show a popup message
Even if you call showWelcomeMessage()
before the function is written in the code, it will still work. Thatβs the power of hoisting.
β What is Hoisting?
Hoisting is JavaScript's default behavior of moving function declarations to the top of the code before execution.
So this will also work:
greet(); // Output: Hello!
function greet() {
console.log("Hello!");
}
β Function Expression
π Definition:
A Function Expression means storing a function inside a variable.
const greetUser = function() {
console.log("Hello, this is a function expression!");
};
Here, the function has no name. Itβs an anonymous function, stored inside the greetUser
variable.
π How to use:
You can call it using the variable name:
greetUser(); // Output: Hello, this is a function expression!
β Important Difference:
Function expressions are not hoisted.
This code will give an error:
sayHello(); // β ERROR: Cannot access 'sayHello' before initialization
const sayHello = function() {
console.log("Hi!");
};
So you must define the function expression before calling it.
π‘ Real-life Example (Function Expression):
Letβs say you are building a music player. You want to create a function that plays a sound when the user clicks play.
const playSound = function() {
console.log("Playing music...");
};
playSound(); // Output: Playing music...
Here, we are storing the function in a variable, which is useful when:
You want to pass it around
Use it as a callback
Or assign different behaviors later
π Comparison Table
Feature | Function Declaration | Function Expression |
Syntax | function funcName() {} | const funcName = function() {} |
Name | Must have a name | Can be anonymous |
Hoisting | β Yes | β No |
Called before definition | β Yes | β No |
Use case | For general reusable functions | When using functions as values |
β When to Use What?
Use Function Declaration When | Use Function Expression When |
You want a simple reusable function | You need a function as a value (like callbacks or passing into another function) |
You want to take advantage of hoisting | You donβt want the function to be hoisted |
Defining utility functions | Creating dynamic or conditional functions |
π Conclusion
Both function declaration and function expression are powerful tools in JavaScript.
Use function declarations when you want to keep code simple and organized.
Use function expressions when you want more control, flexibility, or want to treat functions like values.
β Practice Tip:
Try rewriting the same task using both methods. That will help you understand when to use which style.
π― Mini Project: Simple Grocery Billing System
π¨βπ« Goal:
Create a web-based billing system where the user can:
Enter grocery item names and prices
Add multiple items
Calculate total price using functions
This project will demonstrate:
Function Declaration
Function Expression
DOM manipulation
Real-world logic
π¦ Project Files
index.html
β Structurestyle.css
β Styling (optional)script.js
β Logic using functions
β Step-by-Step Explanation
1οΈβ£ HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Grocery Billing System</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h2>π Grocery Billing</h2>
<label>Item Name:</label>
<input type="text" id="itemName" placeholder="e.g., Rice" />
<label>Item Price:</label>
<input type="number" id="itemPrice" placeholder="e.g., 120" />
<button onclick="addItem()">Add Item</button>
<ul id="itemList"></ul>
<h3>Total: βΉ<span id="totalAmount">0</span></h3>
</div>
<script src="script.js"></script>
</body>
</html>
2οΈβ£ JavaScript (script.js)
// π Function Declaration
function addItem() {
const name = document.getElementById("itemName").value;
const price = parseFloat(document.getElementById("itemPrice").value);
if (!name || !price || price <= 0) {
alert("Please enter valid item name and price!");
return;
}
// Add item to list
displayItem(name, price);
// Add price to total
updateTotal(price);
// Clear inputs
document.getElementById("itemName").value = "";
document.getElementById("itemPrice").value = "";
}
// π Function Expression
const displayItem = function(name, price) {
const itemList = document.getElementById("itemList");
const li = document.createElement("li");
li.textContent = `${name} - βΉ${price}`;
itemList.appendChild(li);
};
// π Another Function Declaration
function updateTotal(price) {
const totalDisplay = document.getElementById("totalAmount");
let currentTotal = parseFloat(totalDisplay.textContent);
currentTotal += price;
totalDisplay.textContent = currentTotal.toFixed(2);
}
3οΈβ£ CSS (Optional: style.css)
body {
font-family: sans-serif;
background-color: #f7f7f7;
display: flex;
justify-content: center;
margin-top: 50px;
}
.container {
background: white;
padding: 20px 30px;
border-radius: 10px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}
input {
margin-bottom: 10px;
display: block;
padding: 5px;
width: 100%;
}
button {
padding: 6px 15px;
background: teal;
color: white;
border: none;
cursor: pointer;
}
ul {
list-style-type: none;
padding-left: 0;
}
π Explanation of Concepts Used
πΉ Function Declaration β addItem()
and updateTotal()
Used for reusable logic
Can be called before defined
Example:
addItem()
is used directly on button click
πΉ Function Expression β const displayItem = function() { ... }
Anonymous function stored in a variable
Can only be used after it's defined
Example: used to dynamically show added items in the list
π§ Why This Project is Helpful?
Benefit | How |
Real-world example | Mimics a real grocery app |
Concept clarity | Clear use of both function types |
Visual output | Changes visible on browser |
Simple HTML + JS | No frameworks needed |
β Bonus Tips for Students
Try adding a "Remove Item" feature using another function expression.
Add date and time when item is added using
new Date()
.Add validations using functions like
isNaN()
.
π Conclusion
This mini project shows how function declaration and function expression can be used together in a real-world scenario. You learn how:
Each function type behaves
To structure your code for clarity
JavaScript is used to handle user interaction in real apps
π What's Next?
In the next note, weβll explore: π Arrow Functions β a modern way to write functions in JavaScript.
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Javascript notes, tutorials, and project ideas β
π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: π In-depth explorations of emerging technologies π‘ Practical tutorials and how-to guides π§Insights on software development best practices πReviews of the latest tools and frameworks π‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letβs connect and grow together! π