3.1 Function Basics
A function is a reusable block of code designed to perform a dedicated computation or action. In JavaScript, functions are first-class citizens: they can be treated as first-class objects, stored in variables, passed into other functions as callbacks, and returned as values.
Figure 3.1: The three capabilities that make JavaScript functions first-class citizens in computer science.
3.2 Function Expressions & Arrow Functions
Arrow functions (=>) introduced in ES6 provide a concise syntax and lexical scoping behavior that fundamentally changes how the this keyword is resolved.
Figure 3.2: Architectural differences between standard functions and arrow functions.
3.3 The Call Stack
The Call Stack is a LIFO (Last In, First Out) data structure used by the JavaScript engine to keep track of execution contexts and return addresses as functions call each other.
Figure 3.3: Call stack frames pushed in calling order. The top frame completes first and is popped off before the caller resumes.
3.4 Closures
A closure is a function bundled together with references to its surrounding lexical environment. In JavaScript, closures allow an inner function to retain persistent access to an outer function's scope variables, even after the outer function has finished executing and returned.
Figure 3.4: Closure preserves access to outer variables even after outer() has exited the call stack.
3.5 The 'this' Keyword
In JavaScript, the this keyword refers to the current execution context object. Crucially, the value of this is determined dynamically at call time by HOW a function is called, not where it was declared (with the sole exception of arrow functions).
Figure 3.5: How 'this' is resolved depending on execution context: standalone invocation, object method call, or lexical inheritance via arrow functions.