🧠 JavaScript Function Concepts: Function Declaration vs Function Expression

Payal PorwalPayal Porwal
7 min read

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

FeatureFunction DeclarationFunction Expression
Syntaxfunction funcName() {}const funcName = function() {}
NameMust have a nameCan be anonymous
Hoistingβœ… Yes❌ No
Called before definitionβœ… Yes❌ No
Use caseFor general reusable functionsWhen using functions as values

βœ… When to Use What?

Use Function Declaration WhenUse Function Expression When
You want a simple reusable functionYou need a function as a value (like callbacks or passing into another function)
You want to take advantage of hoistingYou don’t want the function to be hoisted
Defining utility functionsCreating 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

  1. index.html – Structure

  2. style.css – Styling (optional)

  3. 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?

BenefitHow
Real-world exampleMimics a real grocery app
Concept clarityClear use of both function types
Visual outputChanges visible on browser
Simple HTML + JSNo 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. πŸš€

0
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! 🌟