liveBook · Manning

Scope

As explained in Grokking Simplicity

The region of a program in which a binding can be accessed or referenced.

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

How Grokking Simplicity covers it

How deep it goes
Defines global, local, and inline function scope through examples, then applies scope to state encapsulation.
Examples
Uses greetings, inline callbacks, and a cart-processing queue to demonstrate accessible and hidden bindings.
What it assumes
Assumes basic JavaScript functions and callbacks while defining global, local, and anonymous functions explicitly.
What you can do after
Apply via JavaScript function scope to hide queue state and expose only the operation clients need.
How it connects
Connects scope with functions, callbacks, first-class functions, mutable state, and concurrency.

Also explained in

Compare how 21 books explain scope →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.