Skip to main content

Arrays: Lists of Values

beginner16 min readLesson 34 of 143

Store many values under one name, read any item by index, and meet the built-in methods that do heavy lifting.

An array is an ordered list under one name:

const skills = ["HTML", "CSS", "JavaScript"];

Indexing β€” from zero

skills[0]; // "HTML"       FIRST item is index 0
skills[2]; // "JavaScript"
skills[3]; // undefined    β€” beyond the end is not an error, just nothing

Arrays know their own length:

skills.length; // 3
skills[skills.length - 1]; // last item β€” "JavaScript"

Changing arrays

const todos = ["learn HTML"];
todos.push("learn CSS"); // add to the END β†’ length 2
todos.pop(); // remove from the END β†’ back to 1

The workhorse methods

Each takes a function and builds a new array β€” the original is untouched:

const scores = [90, 72, 88];

scores.map((s) => s * 2); // [180, 144, 176] β€” transform each item
scores.filter((s) => s >= 80); // [90, 88]        β€” keep passing items
scores.find((s) => s < 80); // 72              β€” first match (or undefined)
scores.includes(88); // true
scores.forEach((s) => console.log(s)); // runs the function per item, returns nothing

Read map as "one new item per old item" and filter as "keep the ones that pass". These two cover most list processing you will do this module.

Looping an array β€” the classic pattern

const names = ["Ada", "Grace", "Linus"];

for (let i = 0; i < names.length; i++) {
  console.log(i + ": " + names[i]);
}

Start at 0, keep going while i < names.length. (Later: for...of and forEach shorten this β€” but read and write the classic pattern fluently first.)

What you learned

  • Arrays: ordered lists; index from 0; .length
  • push/pop add/remove at the end
  • map, filter, find, includes, forEach
  • Classic indexed loop over .length

Next: objects β€” labeled data.

Now practice

Arrays: Lists of Values β€” PracticeHands-on practice for β€œArrays: Lists of Values”: apply what you just learned in js-arrays.2 challenges Β· Β· ~10 min