A **function declaration** creates a named function that is **hoisted** — the entire function (name and body) is moved to the top of its scope. This means you can call a declared function before its definition in the source code. Function declarations are block-scoped in strict mode.
1Understanding Function Declaration
A function declaration creates a named function that is hoisted — the entire function (name and body) is moved to the top of its scope. This means you can call a declared function before its definition in the source code. Function declarations are block-scoped in strict mode.
Function declarations are hoisted. Function expressions are NOT. This is why calling a function before its declaration works with declarations but throws ReferenceError with const/let expressions.
// Hoisting: can call before declaration
const result = add(3, 4); // works!
console.log(result); // 7
function add(a, b) {
return a + b;
}2Practical Example
Here is a real-world application of Function Declaration showing how it is used in production JavaScript code.
// Default parameters (ES6+)
function greet(name, greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greet('Alice')); // Hello, Alice!
console.log(greet('Bob', 'Hi')); // Hi, Bob!3Best Practices
Follow these guidelines when working with Function Declaration:
1. Use declarations for main named functions
2. Use descriptive verb-noun names: getUserById, formatDate
3. Keep functions small with a single responsibility
Tip: Function declarations are hoisted. Function expressions are NOT. This is why calling a function before its declaration works with declarations but throws ReferenceError with const/let expressions.
// Hoisting: can call before declaration
const result = add(3, 4); // works!
console.log(result); // 7
function add(a, b) {
return a + b;
}