Programming (JavaScript basics) → Lesson 6

Programming Lesson 6: Arrays, objects & simple algorithms

Working with collections and simple algorithms built on arrays and objects.

Learning goals

  • Understand array basics: indexing, length, push/pop, and iteration patterns.
  • Use objects as key/value maps and know dot vs bracket access.
  • Implement simple algorithms: counting, finding max/min, filtering.
  • Get a basic time/space intuition: larger lists take more work.

Counting occurrences

function countOccurrences(arr, value) {
  let count = 0;
  for (const x of arr) {
    if (x === value) count++;
  }
  return count;
}

countOccurrences([1,2,2,3], 2); // 2

Find max / min

function findMax(arr) {
  if (arr.length === 0) return null;
  let m = arr[0];
  for (const x of arr) if (x > m) m = x;
  return m;
}

Filter items

function filterPositive(arr) {
  const out = [];
  for (const x of arr) if (x > 0) out.push(x);
  return out;
}

filterPositive([-1,2,3]); // [2,3]

Time / space intuition

Simple note: processing a list of n items typically takes time proportional to n (linear). Larger lists take more work; some operations (like searching unsorted lists) cost more than others.

Examples

List of scores

const scores = [5, 10, 7, 10];
const total = scores.reduce((a,b) => a + b, 0); // 32
const avg = total / scores.length; // 8

Object profile

const profile = { username: 'ava', age: 23, settings: { emails: true } };
profile.email = 'ava@example.com';
console.log(profile.settings.emails); // true

countWords

function countWords(str) {
  const words = str.trim().split(/\s+/);
  const map = {};
  for (const w of words) {
    map[w] = (map[w] || 0) + 1;
  }
  return map;
}

countWords('hello hello world'); // { hello: 2, world: 1 }

Practice tasks

  1. Count how many times the number 10 appears in `[10,1,10,3]`. Expected: 2.
  2. Find the maximum in `[5,9,2]`. Expected: 9.
  3. Filter an array to only keep even numbers. Example input `[1,2,3,4]` → expected `[2,4]`.
  4. Given sentence `"a b a"`, countWords should return `{"a":2,"b":1}`.

Common mistakes

  • Mutating arrays unexpectedly (use copies when needed).
  • Accessing undefined keys on objects — check presence before use.
  • Assuming arrays are sorted — searching unsorted lists may miss expected results.