JS Arrays + Loops
---
theme: seriph
title: "JS Arrays + Loops"
info: "Module F-JS-004 — array literals, for loop, for...of, forEach, render a list from data to DOM"
---
# JS Arrays + Loops
---
# The Goal: Render a List from Data
This is the one pattern that ties arrays and loops together.
```js
const tasks = ['Read chapter 3', 'Push to GitHub', 'Review PR'];
const ul = document.querySelector('#task-list');
for (const task of tasks) {
const li = document.createElement('li');
li.textContent = task;
ul.appendChild(li);
}
```
Data lives in an array. A loop turns it into DOM elements. Everything in this deck builds toward this pattern.
> AI tip: When you ask AI to build a feature, describe the data first. "I have an array of tasks, show them as a list" gives AI the context it needs.
---
# What Is an Array?
An **array** stores multiple values in a single variable.
```js
const fruits = ['Apple', 'Banana', 'Orange'];
// Access by index (starting from 0)
console.log(fruits[0]); // 'Apple'
console.log(fruits[1]); // 'Banana'
console.log(fruits[2]); // 'Orange'
// Get the length
console.log(fruits.length); // 3
```
---
# Creating Arrays
```js
// Array literal (preferred)
const colors = ['red', 'green', 'blue'];
// Empty array, then add items
const scores = [];
scores.push(95);
scores.push(87);
console.log(scores); // [95, 87]
// Arrays can hold any type
const mixed = ['hello', 42, true, null];
```
> AI tip: Ask AI "create an array of 5 sample products with name and price" to get practice data instantly.
---
# Modifying Arrays
`push()` adds to the end. `unshift()` adds to the start.
```js
const fruits = ['Apple', 'Banana', 'Orange'];
// Change an item by index
fruits[1] = 'Mango';
console.log(fruits); // ['Apple', 'Mango', 'Orange']
// Add to the end
fruits.push('Kiwi');
console.log(fruits); // ['Apple', 'Mango', 'Orange', 'Kiwi']
// Add to the beginning
fruits.unshift('Cherry');
console.log(fruits); // ['Cherry', 'Apple', 'Mango', 'Orange', 'Kiwi']
```
---
# Removing from Arrays
`pop()` removes from the end. `shift()` removes from the start.
```js
const fruits = ['Cherry', 'Apple', 'Mango', 'Orange', 'Kiwi'];
// Remove from the end
const last = fruits.pop();
console.log(last); // 'Kiwi'
console.log(fruits); // ['Cherry', 'Apple', 'Mango', 'Orange']
// Remove from the beginning
const first = fruits.shift();
console.log(first); // 'Cherry'
console.log(fruits); // ['Apple', 'Mango', 'Orange']
```
---
# Searching Arrays
`includes()` returns true/false. `indexOf()` returns the position (or -1).
```js
const fruits = ['Apple', 'Mango', 'Orange'];
console.log(fruits.includes('Mango')); // true
console.log(fruits.includes('Pineapple')); // false
console.log(fruits.indexOf('Mango')); // 1
console.log(fruits.indexOf('Pineapple')); // -1
```
---
# Arrays vs Strings
```js
const word = 'Apple';
console.log(word[0]); // 'A'
console.log(word.length); // 5
// word[0] = 'B'; // Does NOT work
const letters = ['A', 'B', 'C'];
console.log(letters[0]); // 'A'
console.log(letters.length); // 3
letters[0] = 'Z'; // Works!
console.log(letters); // ['Z', 'B', 'C']
```
**Strings** are immutable. **Arrays** are mutable.
---
# The `for` Loop
Three parts: initialize, condition, update.
```js
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
```
1. **Initialize** — `let i = 0` sets the starting point
2. **Condition** — `i < 5` keeps going while true
3. **Update** — `i++` runs after each iteration
---
# Looping Through an Array
Use `i` to access each element by index.
```js
const fruits = ['Apple', 'Banana', 'Orange'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Apple
// Banana
// Orange
```
---
# `for...of` — The Cleaner Way
When you just need each value and not the index, use `for...of`.
```js
const fruits = ['Apple', 'Banana', 'Orange'];
// Classic for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// for...of — same result, less boilerplate
for (const fruit of fruits) {
console.log(fruit);
}
```
Use `for...of` when you need values. Use classic `for` when you need the index.
---
# `forEach` Method
Arrays have a built-in `forEach` that calls a function for each element.
```js
const fruits = ['Apple', 'Banana', 'Orange'];
fruits.forEach(function (fruit) {
console.log(fruit);
});
// Arrow function version
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
```
`forEach` is an array method (no `break`). `for...of` works on any iterable and supports `break`/`continue`.
> AI tip: AI writes `forEach` often. If you can read it, great. For your own code, use `for...of` -- it is simpler to debug and supports `break`.
---
# Three Ways to Loop — Pick One
| Syntax | Best when |
|---|---|
| `for (let i = 0; ...)` | You need the index |
| `for (const item of arr)` | You need each value |
| `arr.forEach(fn)` | Callback style, no early exit needed |
For this course, default to `for...of` unless you need the index.
---
# Pattern: Render a List from Data
The core pattern of every data-driven UI.
```js
const students = [
{ name: 'Alice', grade: 'A' },
{ name: 'Bob', grade: 'B' },
{ name: 'Charlie', grade: 'C' },
];
const list = document.querySelector('#student-list');
for (const student of students) {
const div = document.createElement('div');
div.textContent = `${student.name}: ${student.grade}`;
list.appendChild(div);
}
```
This is exactly what React and Vue do under the hood.
> AI tip: If AI gives you code with `.map()` or `.filter()`, those are array methods that do the same job as loops. You will see them often in AI-generated code.
---
# Your Turn: Task List
Create `js/task-list.js` linked from an HTML page with a `<ul id="task-list">`.
1. Create an array of 5 tasks (strings)
2. Use a `for...of` loop to create an `<li>` for each task and append it to the list
3. Bonus: add an `if` inside the loop to highlight any task containing the word "GitHub"
---
# Pattern: Filter, Then Render
Loop + conditional: only show items that match.
```js
const scores = [88, 72, 95, 63, 45, 81, 56, 90];
const passList = document.querySelector('#passing');
for (const score of scores) {
if (score >= 60) {
const li = document.createElement('li');
li.textContent = score;
passList.appendChild(li);
}
}
```
Search results, product filters, notifications — all this pattern.
---
# Pattern: Accumulate a Total
Start with a variable at 0, add each element.
```js
const prices = [10, 20, 30];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total); // 60
```
---
# Pattern: Count Matches
Start a counter at 0, increment when a condition is met.
```js
const grades = ['A', 'B', 'A', 'C', 'A', 'B'];
let countA = 0;
for (const grade of grades) {
if (grade === 'A') {
countA++;
}
}
console.log('Number of As:', countA); // 3
```
---
# Putting It All Together
Star rating — generate a visual display from a number.
```js
const rating = 3;
const container = document.querySelector('#stars');
let stars = '';
for (let i = 0; i < 5; i++) {
stars += i < rating ? '★' : '☆';
}
container.textContent = stars; // ★★★☆☆
```
Classic `for` is the right choice here because the loop is index-driven, not data-driven.
> AI tip: Try asking AI: "Generate a star rating display for a rating of 4 out of 5." Compare its approach to yours.
---
# References
- [MDN: Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [MDN: for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)
- [MDN: for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [MDN: forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
- [JavaScript.info: Arrays](https://javascript.info/array)
Topics Covered
- array literals
- for loop
- for...of
- forEach
- pattern: render a list from data to DOM
Content Slides Open fullscreen ↗
Taught In
- Wednesday, 6/17 — JS conditionals · arrays + loops