Scope is the region where a binding can be accessed. JavaScript examples distinguish global definitions, local definitions, and inline anonymous functions. section 12.5
Use scope to control where functions and mutable values can be referenced:
- Define a function globally when other parts of the program should refer to it by name. section 12.5
- Define a named function locally when it needs nearby values but should remain inaccessible outside its scope. section 12.5
- Wrap queue state and its accessing functions in function scope to prevent outside modification and support multiple queues. section 16.4
A private queue
Queue() keeps queue_items and working inside its function scope, then returns only the function client code needs. The returned function can update the queue without exposing its state. section 16.4
function Queue() { #1
var queue_items = [];
var working = false; #2
function runNext() {
if(working)
return;
if(queue_items.length === 0)
return;
working = true;
var cart = queue_items.shift();
calc_cart_total(cart, function(total) {
update_total_dom(total);
working = false;
runNext();
});
}
return function(cart) { #3
queue_items.push(cart);
setTimeout(runNext, 0);
};
}
var update_total_queue = Queue(); #4
Inspect how function scope hides queue variables while exposing a single update function. section 16.4




















