Code / JavaScript from Zero / Unit 3: Loops and arrays

Lists with arrays ऐरे से सूचियाँ

Lesson 6 of 15 · about 14 minutes · Indexes, length, totals, averages, push and includes.

⚡ 0 XP

Step 1 of 2

Arrays and their indexes

78[0]91[1]65[2]88[3]95[4]marks = [78, 91, 65, 88, 95]

An array stores many values in one variable, in order: const marks = [78, 91, 65, 88, 95];

  • Each value has an index, starting at 0: marks[0] is 78, marks[1] is 91
  • marks.length is how many values there are (5)
  • The last value is marks[marks.length - 1]

To add up all marks, loop over the indexes 0 to length − 1 and keep a running total.

Example
const fruits = ["aam", "kela", "seb"];
console.log(fruits[0], fruits.length); // aam 3
for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}

🎯 Challenge: Total and average marks +15 XP

Use a for loop to add up all the numbers in marks into total. Then set average to total divided by the number of subjects (use marks.length). Print both.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • total is 417
  • average is 83.4
  • A loop and marks.length are used
Lesson notes (text version)

1. Arrays and their indexes

An array stores many values in one variable, in order: const marks = [78, 91, 65, 88, 95];

  • Each value has an index, starting at 0: marks[0] is 78, marks[1] is 91
  • marks.length is how many values there are (5)
  • The last value is marks[marks.length - 1]

To add up all marks, loop over the indexes 0 to length − 1 and keep a running total.

                const fruits = ["aam", "kela", "seb"];
console.log(fruits[0], fruits.length); // aam 3
for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}
              

Challenge: Total and average marks

Use a for loop to add up all the numbers in marks into total. Then set average to total divided by the number of subjects (use marks.length). Print both.

2. push, includes and the highest value

Arrays can grow and answer questions:

  • runs.push(73) adds 73 to the end
  • runs.includes(100) is true if 100 is somewhere in the array

To find the highest value, start with the first one and walk through the rest: whenever you see a bigger number, remember it instead.

                const temps = [31, 36, 29];
temps.push(40);
let hottest = temps[0];
for (let i = 1; i < temps.length; i++) {
  if (temps[i] > hottest) hottest = temps[i];
}
console.log(hottest, temps.includes(29)); // 40 true
              

Challenge: A batter’s scores

Virat’s last scores are in runs. In today’s match he scored 73: push it. Then find highest (the biggest score) with a loop, set hasCentury with includes(100), and hasDuck with includes(0).

Search by task, format or tool name.