Skip to content

Function Declaration

A function declaration defines a named function using the function keyword. It is hoisted — meaning it can be called before its definition in the code.

function functionName(parameters) {
// body
return value;
}
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 'Hello, Alice!'

Function declarations are hoisted to the top of their scope:

// ✅ This works!
sayHello(); // 'Hello!'
function sayHello() {
console.log('Hello!');
}
flowchart TD
A["Function Declaration"]
B["function greet(name) { return 'Hello, ' + name; }"]
C["✅ Hoisted to top"]
D["✅ Named — stack traces show the name"]
E["✅ Can be called before definition"]
A --> B
B --> C
B --> D
B --> E
  • Use function declarations for top-level functions
  • Name your functions descriptively (verb + noun)
  • Keep functions small and focused (single responsibility)
// ❌ Don't declare inside if/else (block scoping issues)
if (condition) {
function doSomething() { } // problematic
}
  • Function declarations are hoisted
  • They create named functions
  • Use for main program functions