Lesson 14 of 18

Arrays & Loops 🔁

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Create and manipulate JavaScript arrays
  • Use map, filter, and forEach
  • Dynamically render a list of items to the page

Arrays in JavaScript

JavaScript
const courses = ['Python', 'Web Dev', 'App Dev'];

console.log(courses[0]);    // Python
console.log(courses.length); // 3

courses.push('Data Science'); // add to end
courses.pop();                // remove from end
courses.unshift('Scratch');   // add to beginning

console.log(courses); // ['Scratch', 'Python', 'Web Dev', 'App Dev']

Array Methods: map, filter, forEach

JavaScript
const scores = [88, 72, 95, 61, 79];

// forEach - do something for each item
scores.forEach(score => console.log(score));

// map - transform each item, returns new array
const doubled = scores.map(s => s * 2);
console.log(doubled); // [176, 144, 190, 122, 158]

// filter - keep items that pass a test
const passing = scores.filter(s => s >= 70);
console.log(passing); // [88, 72, 95, 79]
🆕
Chaining

You can chain these: const result = scores.filter(s => s >= 70).map(s => s + 5);

Render a List to the Page

JavaScript
const courses = ['Python', 'Web Dev', 'App Dev'];
const list = document.getElementById('course-list');

// Clear existing
list.innerHTML = '';

// Add each as an li
courses.forEach(course => {
  const li = document.createElement('li');
  li.textContent = course;
  list.appendChild(li);
});
🔁">Dynamic Card Renderer

Create an array of 4 objects: [{name:'Python', level:'Intermediate'},{...}]. Use forEach to dynamically create and append a card div for each one to a grid container.

Quick Check

What does array.push('x') do?

ARemoves x from the array
BAdds x to the end of the array
CChecks if x is in the array

What does array.filter() return?

AModifies the original array
BA new array with items that passed the test
CThe number of items removed

What does array.map() do?

AFilters out items
BTransforms each item and returns a new array
CSorts the array