JavaScript Internals (521 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)
What are the benefits of keeping declarations at the top
It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,
- Gives cleaner code
- It provides a single place to look for local variables
- Easy to avoid unwanted global variables
- It reduces the possibility of unwanted re-declarations
Practical Code Example
javascript
// Benefit: Clear variable scope visibility and eliminates TDZ (Temporal Dead Zone) gotchas
function processOrder(order) {
// Declare all state variables at top of scope:
let subtotal = 0;
let tax = 0;
let total = 0;
subtotal = order.items.reduce((sum, item) => sum + item.price, 0);
tax = subtotal * 0.08;
total = subtotal + tax;
return total;
}