liveBook · Manning

Function code

As explained in Secrets of the JavaScript Ninja, Second Edition

JavaScript source text contained within a function body and executed when the function is called.

Function code is JavaScript placed inside a function. Unlike global code, which runs as the engine encounters it, function code runs only when something calls it—global code, another function, or the browser. section 2.2.2

During page construction, encountering a script element pauses DOM construction while the browser executes JavaScript. Defining a function does not run its body; a call does. 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 listing contrasts a function definition with global code that calls it to add a message to the page. section 2.2.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines function code by placement and explains its invocation, while deferring further differences between code types.
Examples
Uses addMessage to create a list item, append it to the DOM, and demonstrate a function call.
What you can do after
Understand when function-body code executes and distinguish it from global code.
How it connects
Connects function code to global code, function calls, the JavaScript engine, and browser page construction.

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.