Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between: var functionName = function() {} and function functionName() {} in Javascript
In JavaScript, there are two primary ways to define functions: function expressions and function declarations. The key difference lies in how JavaScript processes them during execution.
Function Declaration vs Function Expression
A function declaration is defined using the function keyword followed by the function name, while a function expression assigns a function to a variable.
// Function Declaration
function functionName() {
// code
}
// Function Expression
var functionName = function() {
// code
};
Hoisting Behavior
The main difference is how JavaScript handles hoisting. Function declarations are fully hoisted, meaning they can be called before their definition in the code.
// This works - function declaration is hoisted
functionDisplayTwo();
function functionDisplayTwo() {
console.log("Hello from function declaration!");
}
Hello from function declaration!
However, function expressions are not hoisted in the same way. Only the variable declaration is hoisted, not the function assignment.
try {
// This will cause an error
functionDisplayOne();
} catch (error) {
console.log("Error:", error.message);
}
var functionDisplayOne = function() {
console.log("Hello from function expression!");
};
// Now it works
functionDisplayOne();
Error: functionDisplayOne is not a function Hello from function expression!
Comparison Table
| Aspect | Function Declaration | Function Expression |
|---|---|---|
| Hoisting | Fully hoisted | Only variable is hoisted |
| Call before definition | Yes | No |
| Anonymous function | No | Yes (can be) |
| Conditional creation | Not recommended | Safe |
Complete Example
console.log("=== Function Declaration ===");
// Can call before definition
sayHello();
function sayHello() {
console.log("Hello from declaration!");
}
console.log("=== Function Expression ===");
// Must define before calling
var sayGoodbye = function() {
console.log("Goodbye from expression!");
};
sayGoodbye();
=== Function Declaration === Hello from declaration! === Function Expression === Goodbye from expression!
Conclusion
Function declarations are hoisted and can be called anywhere in their scope, while function expressions must be defined before use. Choose function expressions for conditional creation and function declarations for general-purpose functions.
