Hello readers 👋, welcome back to 7th blog in this JavaScript series.
Imagine you have a recipe book. Every time you want to cook a dish, you don't invent it from scratch – you just open the book, read the recipe, and follow it. That recipe is reusable.
In JavaScript, functions are exactly that – reusable blocks of code that you can "call" whenever you need them.
But did you know there are two ways to create these recipes?
- Function Declaration
- Function Expression
They look similar, but they behave differently in some important ways. Let's explore them with simple examples.
What Are Functions and Why Do We Need Them?
A function is a block of code designed to perform a particular task. It runs only when you call (invoke) it.
Why use functions?
- Reusability – Write once, use many times.
- Organization – Break complex problems into small pieces.
- Readability – Give a name to a block of code, making it easier to understand.
Example:
// A function that adds two numbers
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
console.log(add(10, 2)); // 12
Now let's look at the two ways to create functions.
Function Declaration
A function declaration is the "classic" way to define a function. You start with the function keyword, followed by the function name, parentheses (), and curly braces {}.
Syntax:
function functionName(parameters) {
// code to execute
}
Example:
function multiply(a, b) {
return a * b;
}
console.log(multiply(4, 5)); // 20
Key Feature of Function Declaration
Function declarations are hoisted – they are moved to the top of their scope during compilation. This means you can call a function before you define it in your code.
console.log(greet("Satya")); // "Hello Satya" – works even before definition!
function greet(name) {
return "Hello " + name;
}
This works because JavaScript internally "hoists" the entire function declaration to the top.
Function Expression
A function expression is when you create a function and assign it to a variable. The function itself can be anonymous (without a name) or named.
Syntax:
const variableName = function(parameters) {
// code to execute
};
Example (anonymous):
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
Example (named function expression – rare but possible):
const multiply = function multiplyFn(a, b) {
return a * b;
};
// The name multiplyFn is only accessible inside the function itself.
Key Feature of Function Expression
Function expressions are NOT hoisted. Only the variable declaration is hoisted (if you use var), but the assignment happens at runtime. So you cannot call a function expression before its definition.
console.log(multiply(4, 5)); // ❌ TypeError: multiply is not a function
const multiply = function(a, b) {
return a * b;
};
If you use var instead of const, the variable is hoisted but initialized as undefined, so calling it before definition gives a different error:
console.log(multiply); // undefined (because var is hoisted)
console.log(multiply(4, 5)); // ❌ TypeError: multiply is not a function
var multiply = function(a, b) {
return a * b;
};
Key Differences
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Syntax | function name() {} |
const name = function() {} |
| Hoisting | Fully hoisted – can be called before definition | Not hoisted – cannot be called before definition |
| Requires a name? | Must have a name | Usually anonymous (can be named) |
| Use as a value? | Cannot be used directly as a value | Can be passed as an argument, assigned, etc. |
| Conditional definition? | Not recommended inside conditionals | Can be conditionally defined |
Hoisting Explained Simply
Imagine JavaScript reads your code twice:
- First pass – It collects all function declarations and variable declarations (but not assignments) and moves them to the top.
- Second pass – It executes the code line by line.
For function declarations, the entire function is moved to the top, so it's ready to use anywhere.
For function expressions, only the variable declaration (e.g., var multiply;) is hoisted, but the assignment = function() {} stays in place. So before that line, the variable is undefined.
When to Use Each Type
Use Function Declaration When:
- You want to create a named utility function that you'll call from various places.
- You prefer the flexibility of calling the function anywhere in your scope (hoisting can be convenient).
- You're defining a function at the top level of your script or module.
Example:
// Global helper – can be used anywhere
function formatDate(date) {
return date.toLocaleDateString();
}
Use Function Expression When:
- You need to assign a function to a variable or object property.
- You're passing a function as a callback (e.g., to
setTimeout, event listeners, array methods). - You want to define functions conditionally inside
ifstatements. - You want to limit the function's availability to avoid polluting the global scope.
Example (callback):
setTimeout(function() {
console.log("Time's up!");
}, 1000);
Example (conditional definition):
let greet;
if (language === "en") {
greet = function() { console.log("Hello"); };
} else {
greet = function() { console.log("Hola"); };
}
greet();
Conclusion
-
Function Declaration:
function name() {}– fully hoisted, can be called before definition. -
Function Expression:
const name = function() {}– not hoisted, assigned at runtime, great for callbacks and conditional logic. - Both are useful, and choosing one depends on your need for hoisting, naming, and where the function will be used.
Functions are the building blocks of JavaScript programs. Mastering both ways to create them gives you more flexibility and helps you understand how JavaScript works under the hood.
Keep experimenting in your console. That's where the real learning happens!
Hope you liked this blog. If there's any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.
Top comments (1)
This is not correct. Function expression and assigning a function to a variable are two different things.
Function expression occurs anywhere where the function keyword is used in a position where a statement would be invalid (I.e. as part of an expression). When used in this manner, it effectively works like a "function literal' - creating a function in-place without any assignment. Function expression is seen in IIFEs (hence the name) and also frequently when passing anonymous functions as callbacks.
A function created with function expression CAN be stored in a variable, but doesn't have to be.
developer.mozilla.org/en-US/docs/W...