Hello! Let's dive into your next lesson on functions.
In our last session, we established why functions are so crucial: they are the building blocks for creating reusable and organized code. We saw how they help us follow the "Don't Repeat Yourself" (DRY) principle and keep our programs clean and manageable.
Today, we'll move from the "why" to the "how." You'll learn the two fundamental ways to create functions in JavaScript: Function Declarations and Function Expressions. Understanding the syntax and, more importantly, the key differences in their behavior is a critical step toward writing professional, predictable code. This knowledge will be invaluable as you progress to TypeScript and Next.js, where functions are used everywhere.
Two Ways to Build a Function
In JavaScript, there are several ways to define a function, but we will focus on the two most foundational methods for now.

Let's break down each of these methods.
1. Function Declarations
A Function Declaration is often the first way people learn to create a function. It's straightforward and easy to read. You declare it using the function keyword, followed by a mandatory function name.
The basic structure looks like this:
function functionName(parameters) {
// Code to be executed
}
Let's watch a short video that walks through creating a function with this syntax.
JavaScript Functions Crash Course
This clip from the 'JavaScript Functions Crash Course' on the freeCodeCamp.org channel will show you how to declare a function using the function keyword and then call it.
Watch from 00:13:05 to 00:15:35. Pay attention to the syntax: the function keyword, the name (printMe), the parentheses (), and the curly braces {} that define the function's body.
As the video demonstrated, you define the function once, and then you can call (or invoke) it by using its name followed by parentheses ().
// Function Declaration
function showWelcomeMessage() {
console.log("Welcome! This is a function declaration.");
}
// Calling the function
showWelcomeMessage(); // Output: Welcome! This is a function declaration.
2. Function Expressions
A Function Expression is a bit different. It treats a function as a value, just like a number, string, or boolean. Because a function is a value, you can store it in a variable.
The structure looks like this:
const variableName = function(parameters) {
// Code to be executed
};
Here, we create a function and assign it to a variable (e.g., variableName). Notice that the function itself often doesn't have a name after the function keyword. This is called an anonymous function. The function is then called using the variable's name.
To understand this core idea—that a function is a value—let's go through a short reading.
This article from javascript.info is an excellent resource for deep dives. We'll read the first part, which clearly explains the concept of a function as a value that can be assigned and copied.
Read the sections 'Function expressions' and 'Function is a value'. Focus on how a function can be created on the right side of an assignment (=) and stored in a variable, just like any other piece of data.
Now, let's see a video demonstrating how to create and call a function expression.
JavaScript Functions Crash Course
We'll return to the freeCodeCamp.org crash course. This segment explains Function Expressions by relating them to how you'd normally assign a value to a variable.
Watch from 00:19:07 to 00:21:28. The video contrasts const count = 200 with const printMe = function() { ... }, highlighting that in both cases, you are just assigning a value to a variable.
Here's a code example:
// Function Expression
const showGoodbyeMessage = function() {
console.log("Goodbye! This is a function expression.");
}; // <-- Note the semicolon here, as it's an assignment statement.
// Calling the function via the variable
showGoodbyeMessage(); // Output: Goodbye! This is a function expression.
Test your understanding!
Look at the following code snippet. Is it a Function Declaration or a Function Expression? How do you know?
const calculateArea = function() {
let width = 10;
let height = 5;
console.log(width * height);
};
Show answer
It is a Function Expression. We know this because the function is created on the right-hand side of an assignment operator (=) and is stored in a constant variable named calculateArea. The statement doesn't begin with the function keyword.
The Crucial Difference: Hoisting
So, we have two ways to do the same thing. Why does it matter which one you use? The most important difference lies in a concept called hoisting.
Since you're interested in the "under the hood" details, this is a key behavior to understand. When the JavaScript engine prepares to run your code, it does a first pass and "hoists" (or lifts) certain things to the top of their scope.
-
Function Declarations are fully hoisted. This means the entire function (name and body) is moved to the top. As a result, you can call a function declaration before it appears in your code.
-
Function Expressions are not fully hoisted. The variable declaration (
let myFunction;) is hoisted, but the assignment of the function to that variable is not. This means you will get an error if you try to call a function expression before the line where it is defined.
Let's watch a video that illustrates this difference perfectly.
Function Declarations VS Function Expressions in JavaScript
This video from All Things JavaScript, LLC provides a concise and clear explanation of how hoisting affects declarations versus expressions, complete with code examples and console outputs.
Watch from 00:47 to 04:50. This is the most important part of the lesson. Pay close attention to the TypeError that occurs when trying to call the function expression before it's defined. This visually demonstrates the hoisting difference.
To reinforce this, look at the following image which summarizes the behavior shown in the video.

This behavior is not a bug; it's a fundamental part of how JavaScript works. To dive a little deeper, let's read the definitive explanation.
Let's return to the javascript.info article for a detailed breakdown of this behavior.
Read the sections 'Function Expression vs Function Declaration' and 'When to choose...'. This will solidify your understanding of when the engine creates each function type and gives you practical advice on which to use.
When Should You Use Each?
As a general guideline:
- Use Function Declarations by default. They are often easier to read, and their hoisted nature can make it easier to organize code (e.g., by placing helper functions at the bottom of your file and main logic at the top).
- Use Function Expressions when you need more control, such as when you want to assign a function to a variable conditionally (inside an
ifstatement) or when passing a function as an argument to another function (a concept we will explore later).
Practical Exercises
Time to put this into practice. Open your code editor and create a new file.
Exercise 1: Function Declaration
- Create a function using a function declaration. Name it
calculatePerimeter. - Inside the function, create two variables,
length = 20andwidth = 10. - Calculate the perimeter using the formula
2 * (length + width)and log the result to the console. - Call the function before its declaration in your code to prove that hoisting works.
- Call the function again after its declaration.
Show solution
// 4. Calling the function before it's defined in the code
calculatePerimeter(); // This works because of hoisting!
// 1. Function Declaration
function calculatePerimeter() {
// 2. Variables inside the function
const length = 20;
const width = 10;
// 3. Calculation and output
const perimeter = 2 * (length + width);
console.log(`The perimeter is: ${perimeter}`); // Output: The perimeter is: 60
}
// 5. Calling the function after it's defined
calculatePerimeter(); // Output: The perimeter is: 60
Explanation: The function calculatePerimeter is created using a declaration. The JavaScript engine hoists the entire function to the top of the scope before execution begins, which is why you can call it even on the first line of your script without an error.
Exercise 2: Function Expression
- Create the same
calculatePerimeterfunction, but this time use a function expression and store it in aconstvariable. - Try to call the function before the line where you define it. What happens?
- Move the function call to be after the definition and run the code again.
Show solution
// 2. Calling the function before it's defined
// calculatePerimeter(); // This will cause a ReferenceError!
// Un-comment this line to see the error.
// The error occurs because `calculatePerimeter` isn't initialized yet.
// 1. Function Expression
const calculatePerimeter = function() {
const length = 20;
const width = 10;
const perimeter = 2 * (length + width);
console.log(`The perimeter is: ${perimeter}`);
};
// 3. Calling the function after it is defined and assigned
calculatePerimeter(); // Output: The perimeter is: 60
Explanation: When you try to call calculatePerimeter before its definition, the program crashes. Although the variable calculatePerimeter is hoisted, its value (undefined) is not the function itself. The function is only assigned to the variable when the execution reaches that line. Therefore, you can only call it after it has been assigned.
Conclusion
Great work! You've just learned the two primary ways to create functions and, more importantly, their fundamental difference in behavior. This is a topic that trips up many beginners, so understanding it now gives you a solid advantage.
Key Takeaways:
- Function Declaration: Created with the
function name() {}syntax. It is fully hoisted, meaning you can call it before it's defined in your code. - Function Expression: Created by assigning an anonymous
function() {}to a variable. It is not hoisted, and you can only call it after the line where it is defined. - Functions as Values: The concept behind function expressions is that functions in JavaScript are first-class citizens—they can be treated like any other value (stored in variables, passed around, etc.).
Next Up:
Our functions so far have been static; they do the same thing every time. In our next lesson, we will make them dynamic and truly powerful by learning how to define parameters and pass in arguments. This will allow our functions to accept input and produce different results based on that input.