Function Declaration vs Function Expression in JavaScript
1 . Introduction
Functions are one of the most important building blocks of JS . They allow us to organise code into reusable pieces , making programs easier to write , understand and maintain , but when working with functions , we may come across two common ways of creating them , Function Declaration and Function Expressions .
At first ,they might look almost identical , but there are some important differences in how they are defined , hoisted and used understanding these differences can help us write cleaner JS and avoid unexpected behaviour in our code .
In this blog , we’ll explore Function Declarations vs Function Expressions , understanding how each one works and see when we should use one over the other .
2 . What functions are and why we need them
A function is a self-contained block of reusable code designed to perform a specific task . Think of it like a cooking recipe : we write down the ingredients (inputs ) and the instructions once and we can reuse that recipe to make the dish whenever we want without rewriting the instructions .
A standard function consists of a declaration , parameters (inputs) and a return value (output) .
// 1. Defining the function (The Recipe)
function greetUser(username) {
return "Hello, " + username + "!";
}
// 2. Calling the function (Cooking the Dish)
let message = greetUser("Alice");
console.log(message); // Outputs: Hello, Alice!Why we need Function in JS
Without functions , programming would involve copying and pasting the same blocks of code repeatedly , Function solve several critical software development challenges .
- Code Reusability : Instead of writing the same code over and over , we write it once inside a function and call it whenever needed , This follows the DRY ( Don’t Repeat Yourself) .
- Organisation and Readability : Function let us break large complex codebases into smaller ,manageable chunks . Eg- Instead of reading a massive 500-line script , a developer can look at a clean sequence of functions .
3 . Function Declaration syntax
In Js a function declaration is defined using the function keyword , followed by a mandatory function name , a list of parameters in parentheses and the code body inside curly braces .
function functionName(parameter1, parameter2, parameterN) {
// Code to execute (function body)
return value; // Optional
}// Declaring the function
function greetUser(username) {
return `Hello, ${username}!`;
}
// Executing (calling) the function
const message = greetUser("Alice");
console.log(message); // Output: Hello, Alice!From the above example we can understand the basic of function
functionkeyword : The mandatory keyword that tells JS you are declaring a function .- Function Name : A unique identifier (e.g-
greetUser) used to call the function later . - Parameters : Inputs listed inside parentheses
()and separated by commas . IF our function does not need inputs leave the parentheses empty(). - Function Body : The block of code inside the curly braces
{}that runs whenever the function is invoked . returnStatement : An optional keyword used to send a value back whenever the function was called , If omitted the function returnsundefinedby default .
4 . Function expression Syntax
A JS function expression defines inside an expression , typically by assigning it to a variable , Unlike function declarations , function expressions are not hoisted , meaning they cannot be used before they are defined in the code.
1 . Anonymous Function expressions
The most common syntax omits the function name after the function keyword . The function is invoked using the variable name .
const variableName = function(param1, param2) {
// Code to execute
return value;
}; // Notice the semicolon at the end
// Example usage:
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Outputs: 82 . Named function Expression
We can include a function name after the function keyword , This name is only accessible inside the function’s own scope , making it useful for debugging stack traces or creating recursive calls
const variableName = function functionName(param) {
// 'functionName' is available here for recursion
return param;
};
// Example usage:
const factorial = function computeFactorial(n) {
if (n <= 1) return 1;
return n * computeFactorial(n - 1); // Uses internal name
};
console.log(factorial(5)); // Outputs: 120
// console.log(computeFactorial(5)); // Throws ReferenceError3 . Arrow Function Expression ( Modern ES6+ )
Introduced in modern JS , arrows functions offer a highly concise shorthand for writing function expressions by dropping the function keyword .
const variableName = (param1, param2) => {
return param1 + param2;
};
// If the function has only one parameter, parentheses can be omitted:
const square = x => x * x;5 . Key differences between declarations and expression
The core difference between a declaration and an expression in Js is that declarations create a variable or function structure without producing a value .
Get Anshul tripathi’s stories in your inbox
Join Medium for free to get updates from this writer.
This distinction applies broadly across the language , but it is most critical when comparing Function Declaration and Function Expressions .
6 . Basic idea of hoisting
Hoisting is JS default behaviour of moving declarations to the top of their current scope before the code executes .
Essentially , the JS engine reads your code twice : first to find and allocate memory for all variables and functions ( the compilation phase ) and second to execute the code line by line , because of this you can often reference variables and functions before they are formally written in our file .
Crucially , JS only hoists declarations ,not initialisations ( assignements ) .
1 . Function Hoisting
Function declarations are fully hoisted , the JS engine moves the entire function structure to the top of the scope , allowing you to safely call a function before defining it .
greet(); // Output: "Hello!"
function greet() {
console.log("Hello!");
}2 . Variable Hoisting ( var vs let & const )
The keyword you use to declare a variable completely changes how it handles hoisting .
Using var
When you use var , the variable declaration is hoisted and automatically given a placeholder value of undefined
console.log(user); // Output: undefined (No crash)
var user = "Alice";
console.log(user); // Output: "Alice"Behind the scenes the engine sees the code like this :
var user; // Declaration is hoisted to the top!
console.log(user); // Value is undefined
user = "Alice"; // Assignment stays right where it was
console.log(user); // Value is now "Alice"Using let and const
Variable declared with let and const are also hoisted , but they are not initialised with any default value . They sit in a locked state called the Temporal Dead Zone ( TDZ) from the start of the block until the engine reaches the line where they are declared .
Trying to access them early causes the application to crash with a ReferenceError .
console.log(age); // Throws ReferenceError: Cannot access 'age' before initialization
let age = 25;3 . Function Expression and Arrow Functions
If you assign a function to a variable , it follows the hoisting rules of that specific variable keyword hoisting not function hoisting rules .
sayHi(); // Throws TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi!");
};Because sayHi was declared with var , only the variable declarations was hoisted (as undefined ) . You cannot invoke undefined as a function , if you used let or const here , it would throw a ReferenceError instead .
7 . When to use each type
You should use let for variables that will change and const for variables that must remain constant.
In modern JavaScript, you should almost never use var. Choosing between let and const depends entirely on whether you need to reassign the variable later.
Use const by Default
You should use const for around 80-90% of your variables. It prevents accidental bugs by ensuring a variable cannot be reassigned to a completely new value.
- Fixed values:
const pi = 3.14; - DOM elements:
const submitBtn = document.getElementById('submit'); - Functions:
const fetchData = () => {}; - Objects and Arrays: (Even if you change the properties inside an object or array, the variable itself isn’t being reassigned).
const user = { name: "Alice" };
user.name = "Bob"; // This is perfectly fine!
user = { name: "Charlie" }; // Throws TypeError (Cannot reassign)8 . Conclusion
Understanding the difference between Function Declaration and Function Expression is an important part of writing clean and predictable JS , While both are used to create function , they differ in syntax , hoisting behaviour and how they are commonly used .
Function declaration are great when we want to define reusable functions that can be called before their definition . Function expressions , on the other hand provide more flexibility and are especially useful when working with callbacks , conditional logic , or assigning functions to variables .
Once you understand these differences , choosing between the two becomes much easier and your JS code becomes more intentional and readable .
Keep learning , Keep exploring and Keep building !!!!!
Please share your feedback with us !!!!
Thank you 😀










