Function Declarations & Expressions in JavaScript
🟢 Beginner Level | JavaScript Core Syntax
📖 Definition
A Function Declaration uses the function keyword to define a named, hoisted block of code. A Function Expression assigns an anonymous or named function to a variable, evaluating only when execution reaches its assignment line.
🌍 Multilingual Explanations
English
Function declarations are hoisted to the top of their scope during V8 engine creation phase, allowing them to be invoked before their line definition. Expressions are evaluated during execution phase.
Hindi
Function declaration function greet() { ... } code start hone par hoists ho jati hai. Function expression variable assignment line par initialize hota hai.
Marathi
Function declarations scope madhye top var hoist hotat, mhanun tyna aadhi call karta yete.
Hinglish
Declarations are hoisted (pehle memory milti hai), Jabki Expressions non-hoisted hote hain (variable initialization line par hi execute hote hain).
⚡ Execution Flow in V8 Engine
- Creation Phase: V8 parser scans code and allocates memory for Function Declarations in the Memory Heap.
- Execution Phase: Function Expressions remain
uninitialized(forlet/const) orundefined(forvar) until code execution hits their assignment line. - Invocation: Calling a function pushes a new Execution Context onto the Call Stack with its own arguments and local variable environment.
💡 Production Code Example
// 1. Hoisted Function Declaration (Can be called before definition)
console.log(calculateTotal(100, 0.18)); // Output: 118
function calculateTotal(price, taxRate) {
return price + (price * taxRate);
}
// 2. Function Expression (Cannot be called before this line)
const formatCurrency = function(amount) {
return "$" + amount.toFixed(2);
};
console.log(formatCurrency(118)); // Output: "$118.00"
⚠️ Common Pitfalls & Warnings
Temporal Dead Zone with Expressions: Calling a const or let function expression before its definition line throws a ReferenceError: Cannot access before initialization.
🎯 Tiered Practice Exercises
- Beginner: Write a function declaration
multiply(a, b)and call it before its line position. - Intermediate: Convert
multiply(a, b)into a named function expression. - Advanced: Demonstrate how Function Declarations behave when placed inside conditional
ifblocks in strict mode.
🧭 Navigation
← Module Hub | Functions Hub | 02. Arrow Functions & Lexical 'this' →