Search lands in PR-5.1 (Pagefind).

Explanation Beginner

Chapter 4 Updated

Functions & Variable Environments

How each function creates its own isolated world of variables — and why same-named names never collide.

  • Full 14m
  • Revision 3m
  • Flow 2m

Every call = new world

One invocation, one Execution Context.

  • A call creates a brand new Execution Context with its own Variable Environment.
  • Parameters, locals, and nested function declarations live inside it.
  • Return value is sent back; the entire context is destroyed after return.
  • Calling the same function N times = N independent contexts, no shared state.

Same name, different memory

Why local variables never collide.

  • var x = 10 in a() and var x = 100 in b() live in different memory slots.
  • Neither touches the global x.
  • When a() returns, its x is gone — b() can’t read it.
  • This isolation is what a “scope” is, underneath the word.

Missing var is dangerous

Implicit globals and strict mode.

  • x = 10 (no var/let/const) → writes to the global variable.
  • In non-strict mode, it silently creates one if none exists.
  • In strict mode → ReferenceError: x is not defined.
  • Prefer strict mode everywhere to catch this at the source.

Lexical scoping

Scope is decided where you write, not where you call.

  • Function a defined at the top level → its scope chain goes through the global scope.
  • Even if a is called from inside b, it cannot see b’s locals.
  • JavaScript uses static (lexical) scoping, not dynamic.
  • This is why closures work — inner functions remember the scope they were born into.

Primitives vs objects

By value, by reference.

  • Primitives (number, string, boolean, null, undefined, symbol, bigint) → passed by value.
  • Objects (arrays, objects, functions) → passed by reference (technically, a reference copy).
  • Mutating o.val inside the function changes the caller’s object.
  • Reassigning the parameter (o = {}) only changes the local variable.

The arguments object

Every regular function gets one.

  • Array-like, not an array — has length and indexed access, but no map/forEach.
  • Available in every non-arrow function, regardless of declared parameters.
  • Arrow functions do not have their own arguments — they borrow the enclosing one.
  • Modern code prefers rest params (...args) — cleaner and array-native.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.