Read an outer variable from an inner function.

closure-reads A closure lets a function remember variables from the scope where it was created. Here the function reads `base` from the outer scope.

Closure Reads

base
closure_reads.js
Replay: real traced execution (multi-file project)
const base = 10;

function addBase(value) {
  return value + base;
}

const total = addBase(5);

console.log("base=" + base);
console.log("total=" + total);
const base = 20;

function addBase(value) {
  return value + base;
}

const total = addBase(5);

console.log("base=" + base);
console.log("total=" + total);
const base = 30;

function addBase(value) {
  return value + base;
}

const total = addBase(5);

console.log("base=" + base);
console.log("total=" + total);
  1. base ← 10

    1const base→ 10 = 10; //@base=20, 3023function addBase(value) {4  return value + base;5}67const total = addBase(5);
  2. //@base=20, 30 function addBase(value)

    1const base = 10; //@base=20, 3023function addBase(value5) {4  return value + base10;5}
  3. total ← 15

    4  return value + base;5}67const total→ 15 = addBase(5);89console.log("base=" + base10);10console.log("total=" + total15);
    outputbase=10
    total=15
  1. base ← 20

    1const base→ 20 = 20;23function addBase(value) {4  return value + base;5}67const total = addBase(5);
  2. function addBase(value)

    1const base = 20;23function addBase(value5) {4  return value + base20;5}
  3. total ← 25

    4  return value + base;5}67const total→ 25 = addBase(5);89console.log("base=" + base20);10console.log("total=" + total25);
    outputbase=20
    total=25
  1. base ← 30

    1const base→ 30 = 30;23function addBase(value) {4  return value + base;5}67const total = addBase(5);
  2. function addBase(value)

    1const base = 30;23function addBase(value5) {4  return value + base30;5}
  3. total ← 35

    4  return value + base;5}67const total→ 35 = addBase(5);89console.log("base=" + base30);10console.log("total=" + total35);
    outputbase=30
    total=35