Lesson 14 of 18
Arrays & Loops 🔁
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?
What does array.filter() return?
What does array.map() do?