Chapter 3 of 12
3.1 Functions & Scope Architecture
Functions in JavaScript are first-class objects. They can be stored in variables, passed as arguments, and returned from other functions.
Arrow Functions vs Declarationsjavascript
// Function Declaration (Hoisted completely)
function multiply(a, b) {
return a * b;
}
// Arrow Function (No lexical 'this', 'arguments', or 'prototype')
const add = (a, b) => a + b;
// Pure Function Example
const pureSquare = (x) => x * x; // No side effects, deterministic output3.2 Execution Context, Call Stack & Closures
When JS code runs, an Execution Context is created in two phases: Creation Phase (Memory Allocation/Hoisting) and Execution Phase (Line-by-line evaluation).
Closures & Memory Retentionjavascript
function createCounter(initialValue = 0) {
let count = initialValue; // Retained via Lexical Environment Closure
return {
increment() { count++; return count; },
decrement() { count--; return count; },
getValue() { return count; }
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.getValue()); // 11 (count remains encapsulated!)What is a Closure?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). Closures allow inner functions to access outer scope variables even after the outer function has returned.
3.3 The `this` Keyword Masterclass
The value of this depends entirely on HOW a function is invoked:
Implicit vs Explicit Bindingjavascript
const user = {
name: 'Developer',
greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
};
// 1. Implicit Binding
user.greet('Hello'); // 'Hello, Developer'
// 2. Explicit Binding (call, apply, bind)
const externalFn = user.greet;
externalFn.call({ name: 'Alex' }, 'Welcome'); // 'Welcome, Alex'
externalFn.apply({ name: 'Sarah' }, ['Hey']); // 'Hey, Sarah'
const boundFn = externalFn.bind({ name: 'BoundUser' });
boundFn('Hi'); // 'Hi, BoundUser'