liveBook · Manning

Function scope

As explained in Secrets of the JavaScript Ninja, Second Edition

A scope in which a variable is visible throughout the entire function body rather than being limited to a block.

Calling a function creates a scope for its local variables: they are visible inside that function, but hidden from outside code. JavaScript’s lexical environment is the internal mechanism behind scoping; “scope” is the common shorthand. section 5.4 section 11.1.1

Historically, before ES6, JavaScript associated lexical environments only with functions, so variables could only be function-scoped. ES6 added scopes for blocks and catch clauses, addressing a source of confusion for developers familiar with other C-like languages. section 5.4

Function scope can also hide implementation details. A module function can keep variables such as a click counter private while returning an interface whose methods use closures to retain access to them. section 11.1.1

Listing 11.1. The module pattern
const MouseCounterModule = function() {                         #A
  let numClicks = 0;                                            #B
  const handleClick = () => {                                   #C
    alert(++numClicks);                                         #C
  };                                                            #C
  
  return {                                                      #D
    countClicks: () => {                                        #D
      document.addEventListener("click", handleClick);          #D
    }                                                           #D
  };                                                            #D
}();

assert(typeof MouseCounterModule.countClicks === "function",    #E
       "We can access module functionality");                   #E
assert(typeof MouseCounterModule.numClicks === "undefined"      #F
    && typeof MouseCounterModule.handleClick === "undefined" ,  #F
       "We cannot access internal module details");             #F

The module pattern listing shows a function-local click counter retained by a returned public interface. section 11.1.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines lexical environments and contrasts pre-ES6 function-only scope with ES6 block and catch scopes, without detailing runtime internals.
Examples
Uses a function-local click counter and a returned module interface to illustrate private variables retained by closures.
What you can do after
Understand how function calls isolate variables and how closures can preserve access to them through a module interface.
How it connects
Connects function scope to lexical environments, block scope, closures, and JavaScript modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.