Skip to main content
InterviewHubPRO
Section Overview
Q150

Question 150 of 536

Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)

28%
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,

  1. Gives cleaner code
  2. It provides a single place to look for local variables
  3. Easy to avoid unwanted global variables
  4. 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;
}