CodePeek · Free JavaScript classroom challenge

Which array changes?

TEACHER KEY · Answers and explanations

Same snippets and order as the learner handout and interactive quiz. Keep this key separate until learners have made their predictions.

1. slice vs splice

const letters = ["a", "b", "c"];
console.log(letters.slice(1).join(""));
letters.splice(1, 1);
console.log(letters.join(""));

Correct output

bc
ac
  1. slice(1) copies elements from index 1 to the end, without changing letters: "b" and "c".
  2. splice(1, 1) removes one element at index 1 from the original array: "b".
  3. The remaining array is ["a", "c"], so join prints ac.

Takeaway: slice copies a range; splice changes the original array.

2. map

const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(nums.join(","));
console.log(doubled.join(","));

Correct output

1,2,3
2,4,6
  1. map calls the callback for each element and collects its returned values into a new array.
  2. This callback only multiplies a number; it does not mutate nums.
  3. The original remains 1,2,3 and the new array contains 2,4,6.

Takeaway: map returns a new array; what its callback does still matters.

3. References

const first = [1, 2];
const second = first;
second[0] = 9;
console.log(first.join(","));

Correct output

9,2
  1. Assigning first to second copies the reference, not the array.
  2. Both variables refer to the same array. Updating second[0] updates that shared array.
  3. Reading first therefore sees 9 at index 0 and 2 at index 1.

Takeaway: An array assignment does not create an independent copy.