JavaScript: Arrays and Loops

contain

Arrays

What is an Array?

An array stores multiple values in a single variable:

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

// Get the last item
console.log(fruits[fruits.length - 1]); // 'Orange'

Modifying Arrays

push() adds to the end (most common). unshift() adds to the start.

const fruits = ['Apple', 'Banana', 'Orange'];

// Change an item
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() from the start. Use splice() to remove by index.

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 if not found).

const fruits = ['Apple', 'Mango', 'Orange'];

// Find the index of an item
console.log(fruits.indexOf('Mango'));     // 1
console.log(fruits.indexOf('Pineapple')); // -1 (not found)

// Check if item exists
console.log(fruits.includes('Mango'));    // true
console.log(fruits.includes('Pineapple')); // false

Array vs String

const word = 'Apple';
console.log(word[0]);     // 'A'
console.log(word.length); // 5
// word[0] = 'B';         // This will NOT work!

const letters = ['A', 'B', 'C'];
console.log(letters[0]);     // 'A'
console.log(letters.length); // 3
letters[0] = 'Z';            // This works!
console.log(letters);        // ['Z', 'B', 'C']
  • Strings are immutable (cannot be changed)
  • Arrays are mutable (can be changed)

Loops

The for Loop

The three parts: initialize, check condition, update. The loop stops when the condition is false.

for (let i = 0; i < 5; i++) {
  console.log(i);
}
// Output: 0, 1, 2, 3, 4
  1. Initialize: let i = 0 - starting point
  2. Condition: i < 5 - keep going while true
  3. Update: i++ - what to do after each loop

Looping Through Arrays

The most common loop pattern: go from index 0 to array.length - 1.

const fruits = ['Apple', 'Banana', 'Orange'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Orange

The while Loop

A while loop checks the condition before each iteration. Make sure the counter updates, or you'll loop forever.

let count = 0;

while (count < 5) {
  console.log(count);
  count++;
}
// Output: 0, 1, 2, 3, 4

Use while when you don't know how many iterations you need.

Common Loop Patterns

Start with total = 0, then add each element. This works for any cumulative calculation.

const numbers = [10, 20, 30];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum = sum + numbers[i];
}
console.log(sum); // 60

Common Loop Patterns (cont.)

Use break to exit the loop once you find what you're looking for.

const names = ['Alice', 'Bob', 'Charlie'];
let found = false;

for (let i = 0; i < names.length; i++) {
  if (names[i] === 'Bob') {
    found = true;
    break; // Exit the loop early
  }
}
console.log(found); // true

break and continue

break exits the entire loop. continue skips the current iteration and moves to the next.

// break: exit the loop entirely
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);
}
// Output: 0, 1, 2, 3, 4

// continue: skip to next iteration
for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);
}
// Output: 0, 1, 3, 4

for...of Loop

A cleaner way to loop through arrays when you don't need the index.

const fruits = ['apple', 'banana', 'cherry'];

// 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 just need each value. Use classic for when you need the index.

forEach Method

Arrays have a built-in forEach method that calls a function for each element.

const fruits = ['apple', 'banana', 'cherry'];

fruits.forEach(function(fruit) {
  console.log(fruit);
});

// With arrow function
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

forEach vs for...of: forEach is an array method (can't use break). for...of works on any iterable and supports break/continue.

Practical Examples

Processing Form Radio Buttons

Loop through radio buttons and check the checked property to find which one is selected.

<form id="my-form">
  <label><input type="radio" name="color" value="red">Red</label>
  <label><input type="radio" name="color" value="blue">Blue</label>
  <label><input type="radio" name="color" value="green">Green</label>
</form>
const colors = document.getElementById('my-form').elements['color'];

let selected;
for (let i = 0; i < colors.length; i++) {
  if (colors[i].checked) {
    selected = colors[i].value;
    break;
  }
}
console.log(selected);

Building a String from Array

Build output by concatenating each item in a loop. Useful for creating lists or formatted text.

const items = ['Milk', 'Bread', 'Eggs'];
let list = 'Shopping list:\n';

for (let i = 0; i < items.length; i++) {
  list = list + '- ' + items[i] + '\n';
}

console.log(list);
// Shopping list:
// - Milk
// - Bread
// - Eggs

Counting Items

The counter pattern: start at 0, increment when a condition is met.

const grades = ['A', 'B', 'A', 'C', 'A', 'B'];
let countA = 0;

for (let i = 0; i < grades.length; i++) {
  if (grades[i] === 'A') {
    countA++;
  }
}

console.log('Number of As:', countA); // 3

Practice

Write code that:

  1. Creates an array of 5 numbers
  2. Loops through and finds the largest number
  3. Displays the result
const numbers = [23, 45, 12, 67, 34];

// Your code here - find the largest number

console.log('Largest:', largest);  // Should be 67

References