Module 5: Arrays, Objects, and Collections
Arrays and Indexing
Create arrays, access elements, and understand mutation and copying.
Arrays store ordered values and use zero-based numeric indexes. Arrays can grow or shrink, and they can contain values of different types, although keeping a consistent element shape often makes application code easier to maintain.
const topics = ["variables", "functions", "objects"];
console.log(topics[0]); // "variables"
console.log(topics.length); // 3
topics.push("async JavaScript");
console.log(topics.at(-1)); // last item
Mutation and copies#
Methods like push, pop, splice, and direct index assignment mutate an array. Methods like map, filter, slice, and concat return a new array. Know which behaviour a method has so shared state is changed intentionally.
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3]
Spread makes a shallow copy. If the array contains objects, the object references are still shared.
Check and find#
Use Array.isArray(value) to check for arrays. Methods such as includes, indexOf, find, and findIndex help search; choose one based on whether you need a boolean, an index, or a matching value.
Common mistakes#
- Accessing an index that does not exist returns
undefined. delete array[index]leaves an empty slot rather than shifting values; usesplicewhen removing by index.- Sorting numbers with
sort()without a comparator sorts their string representations.
Practice#
Create a list of course topics, add one, remove one, and make a separate shallow copy before transforming it.