Foundations
Arrays
Arrays keep related values in order and let code read values by index.
array index
Array indexes start at zero, so `scores[0]` reads the first value.
Arrays
arrays.js
Replay: real traced execution (multi-file project)
const scores = [82, 91, 76];
const bonus = 5;
const firstScore = scores[0];
const adjustedScore = scores[1] + bonus;
console.log("first=" + firstScore);
console.log("adjusted=" + adjustedScore);
const scores = [82, 91, 76];
const bonus = 0;
const firstScore = scores[0];
const adjustedScore = scores[1] + bonus;
console.log("first=" + firstScore);
console.log("adjusted=" + adjustedScore);
const scores = [82, 91, 76];
const bonus = 10;
const firstScore = scores[0];
const adjustedScore = scores[1] + bonus;
console.log("first=" + firstScore);
console.log("adjusted=" + adjustedScore);
scores ← 82,91,76, bonus ← 5, firstScore ← 82, scores[0] ← 82
1const scores→ 82,91,76 = [82, 91, 76];2const bonus→ 5 = 5; //@bonus=0, 103const firstScore→ 82 = scores[0]→ 82;4const adjustedScore→ 96 = scores[1]→ 91 + bonus5;56console.log("first=" + firstScore82);7console.log("adjusted=" + adjustedScore96);outputfirst=82 adjusted=96
scores ← 82,91,76, bonus ← 0, firstScore ← 82, scores[0] ← 82
1const scores→ 82,91,76 = [82, 91, 76];2const bonus→ 0 = 0;3const firstScore→ 82 = scores[0]→ 82;4const adjustedScore→ 91 = scores[1]→ 91 + bonus0;56console.log("first=" + firstScore82);7console.log("adjusted=" + adjustedScore91);outputfirst=82 adjusted=91
scores ← 82,91,76, bonus ← 10, firstScore ← 82, scores[0] ← 82
1const scores→ 82,91,76 = [82, 91, 76];2const bonus→ 10 = 10;3const firstScore→ 82 = scores[0]→ 82;4const adjustedScore→ 101 = scores[1]→ 91 + bonus10;56console.log("first=" + firstScore82);7console.log("adjusted=" + adjustedScore101);outputfirst=82 adjusted=101
Follow the Array
scoresstarts as[82, 91, 76].bonusstarts at5.firstScore = scores[0]reads82.adjustedScore = scores[1] + bonusadds91 + 5.- The program prints
first=82andadjusted=96. | bonus | first score | adjusted score | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |
Exercise: arrays.js
Reproduce first=82 and adjusted=96, then try bonus 0 and 10 and predict each adjusted score before running it.