JavaScript & V8 Internals (536 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)
What are the benefits of keeping declarations at the top
junior LevelCode ExampleHTTP & REST APIs
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;
}