liveBook · Manning

Global code

As explained in Secrets of the JavaScript Ninja, Second Edition

JavaScript source text that is not enclosed in a function and is evaluated in the global execution context.

Global code is JavaScript placed outside every function. In a browser, the engine executes it automatically, line by line, as encountered; function code runs only when called. During page-building, encountering a script pauses HTML parsing and DOM construction while its JavaScript executes. section 2.2.2 section 2.2

Listing 2.2. Global and function JavaScript code
<script>
  function addMessage(element, message){            
    var messageElement = document.createElement("li");             #A
    messageElement.textContent = message;                          #A
    element.appendChild(messageElement);                           #A
  }

  var first = document.getElementById("first");                    #B
  addMessage(first, "Page loading");                               #B
</script>

The function definition and call sit in global code; the function body runs when called. section 2.2.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines code by placement and contrasts automatic line-by-line execution with function code that must be called.
Examples
Uses an addMessage script that fetches a DOM element and calls a function, plus an assertion checking global this against window.
What you can do after
Understand when top-level statements run and how their execution differs from function code.
How it connects
Connects global code to function code, JavaScript execution, and browser page-building.

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.