Variables store values that later expressions can reuse.

const Use `const` when a local binding should not be reassigned.

Variables

unitPrice
variables.js
Replay: real traced execution (multi-file project)
const unitPrice = 12;
const quantity = 3;
const total = unitPrice * quantity;

console.log("unit=" + unitPrice);
console.log("total=" + total);
const unitPrice = 8;
const quantity = 3;
const total = unitPrice * quantity;

console.log("unit=" + unitPrice);
console.log("total=" + total);
const unitPrice = 20;
const quantity = 3;
const total = unitPrice * quantity;

console.log("unit=" + unitPrice);
console.log("total=" + total);
  1. unitPrice ← 12, quantity ← 3, total ← 36

    1const unitPrice→ 12 = 12; //@unitPrice=8, 202const quantity→ 3 = 3;3const total→ 36 = unitPrice→ 12 * quantity3;45console.log("unit=" + unitPrice12);6console.log("total=" + total36);
    outputunit=12
    total=36
  1. unitPrice ← 8, quantity ← 3, total ← 24

    1const unitPrice→ 8 = 8;2const quantity→ 3 = 3;3const total→ 24 = unitPrice→ 8 * quantity3;45console.log("unit=" + unitPrice8);6console.log("total=" + total24);
    outputunit=8
    total=24
  1. unitPrice ← 20, quantity ← 3, total ← 60

    1const unitPrice→ 20 = 20;2const quantity→ 3 = 3;3const total→ 60 = unitPrice→ 20 * quantity3;45console.log("unit=" + unitPrice20);6console.log("total=" + total60);
    outputunit=20
    total=60

Follow the Total

  1. unitPrice starts at 12.
  2. quantity starts at 3.
  3. total = unitPrice * quantity multiplies 12 * 3.
  4. total becomes 36.
  5. The program prints unit=12 and total=36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |

Exercise: variables.js

Reproduce unit=12 and total=36, then try unitPrice 8 and 20 and predict each total before running it.