Foundations
Variables
Variables store values that later expressions can reuse.
const
Use `const` when a local binding should not be reassigned.
Variables
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);
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
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
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
unitPricestarts at12.quantitystarts at3.total = unitPrice * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit=12andtotal=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.