Function Declaration
Function Declaration
Section titled “Function Declaration”Introduction
Section titled “Introduction”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.
Syntax
Section titled “Syntax”function functionName(parameters) { // body return value;}Example
Section titled “Example”function greet(name) { return `Hello, ${name}!`;}
console.log(greet('Alice')); // 'Hello, Alice!'Hoisting
Section titled “Hoisting”Function declarations are hoisted to the top of their scope:
// ✅ This works!sayHello(); // 'Hello!'
function sayHello() { console.log('Hello!');}Visual Explanation
Section titled “Visual Explanation”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 --> EBest Practices
Section titled “Best Practices”- Use function declarations for top-level functions
- Name your functions descriptively (verb + noun)
- Keep functions small and focused (single responsibility)
Common Mistakes
Section titled “Common Mistakes”// ❌ Don't declare inside if/else (block scoping issues)if (condition) { function doSomething() { } // problematic}Summary
Section titled “Summary”- Function declarations are hoisted
- They create named functions
- Use for main program functions