Function Declaration is a function declared separately as an instruction. Function Expression is a function created as part of an expression. Main difference: Function Declaration is fully hoisted, while Function Expression — only the variable is hoisted.
A function declared separately:
function sayHello() {
return 'Hello!';
}A function created as part of an expression:
const sayHello = function() {
return 'Hello!';
};The difference between Function Declaration and Function Expression is in how and when they are created. This is important for understanding how JavaScript works.
A function declared separately:
function sayHello() {
return 'Hello!';
}A function created as part of an expression:
const sayHello = function() {
return 'Hello!';
};// Can be called before declaration
console.log(sayHello()); // 'Hello!'
function sayHello() {
return 'Hello!';
}// Cannot be called before creation
console.log(sayHello()); // Error!
const sayHello = function() {
return 'Hello!';
};// Function Declaration is fully hoisted
declared(); // Works
function declared() {
console.log('Works');
}
// Function Expression — only variable is hoisted
// expressed(); // Error! expressed is still undefined
var expressed = function() {
console.log('Doesn't work');
};// Function Declaration visible everywhere in its scope
if (true) {
function test() { return 'Works'; }
}
// Function Expression — only after declaration
if (true) {
var expr = function() { return 'Works'; };
// expr(); // Only can be called here
}// Main functions of program
function calculateSum(a, b) {
return a + b;
}
function validateForm(data) {
// validation logic
}// Functions as values
const handlers = {
click: function() { /* click handling */ },
hover: function() { /* hover handling */ }
};
// Conditional creation
let sayHi;
if (condition) {
sayHi = function() { return 'Hi!'; };
} else {
sayHi = function() { return 'Hello!'; };
}// ❌ Error with Function Expression
console.log(myFunc()); // TypeError!
const myFunc = function() {
return 'Result';
};
// ✅ Correct with Function Declaration
console.log(declaredFunc()); // Works
function declaredFunc() {
return 'Result';
}// ❌ With var variable is hoisted, but value isn't
console.log(func()); // TypeError! func undefined
var func = function() {
return 'Result';
};
// ✅ Function Declaration is fully hoisted
console.log(declared()); // Works
function declared() {
return 'Result';
}Understanding the difference helps write more predictable code and avoid errors with function declaration order.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪