Keep an ordered collection and understand mutation
An array stores indexed elements and has a length property. Indexing starts at zero. Several familiar methods modify the original array, so know whether a method changes data before sharing that array with other code.
const lessons = ['Variables', 'Loops'];
lessons.push('Functions');
console.log(lessons.length); // 3
console.log(lessons[0]); // Variables
const removed = lessons.pop();
console.log(removed); // Functions
lessons.unshift('Introduction');
console.log(lessons); // ['Introduction', 'Variables', 'Loops']push/pop work at the end. unshift/shift work at the beginning. Their return values differ: push returns the new length, while pop returns the removed element.
splice versus slice
const marks = [10, 20, 30, 40];
const copy = marks.slice(1, 3);
console.log(copy); // [20, 30]
marks.splice(1, 2, 25);
console.log(marks); // [10, 25, 40]slice returns a shallow portion and leaves the original array's sequence unchanged. splice removes/inserts in the original. The second splice argument is a removal count, not an end index.
Numeric sorting
const values = [2, 10, 3];
values.sort((a, b) => a - b);
console.log(values); // [2, 3, 10]Without a comparator, sort uses string-based ordering and can place 10 before 2. sort and reverse mutate the array. If you need to preserve it, copy first or use a supported nonmutating alternative appropriate to the project's runtime.
Shallow copies and holes
Copying an array does not deeply clone object elements. Both arrays can still reference the same student object. Assigning to an index far beyond length creates empty slots; empty slots are not identical in every array operation to explicit undefined values. Prefer sequential construction over sparse arrays for ordinary lesson lists.
Practice
- Remove the first item and inspect shift's returned value.
- Delete one middle lesson with splice.
- Sort a copied marks array and confirm the original order remains.
- Predict reading index equal to length: normally undefined, not the final element.