Copying and Changing Array Ranges
Introduction
Welcome back to Storing and Updating Lists with JavaScript Arrays. In this lesson, we’ll work with ranges inside a list, not just its ends. We’ll learn to copy part of an array with slice(), then use splice() to remove, insert, or replace values in the original. By the end, we’ll be able to choose the right method when we want to keep a copy or change a route in place.
A Reminder About String slice()
As you may recall from the strings course, slice(start, end) selects part of a string. The value at start is included, but the value at end is not. For example, a slice from position 1 to position 3 includes positions 1 and 2. With arrays, slice() follows the same position rule but returns a new array containing the selected values. That makes it useful when we want a section of a list without changing the original.
Copying a Range with slice()
Let’s use slice() to copy the middle stops and then copy the tail. The first call starts at position 1 and ends before position 3; the second starts at position 2 and leaves the end out. When the end is omitted, slice() copies through the array’s final value. Neither call changes stops. The snippets in this lesson continue one program in order. Using slice(0) would copy the whole flat list, starting at position 0 and continuing to the end.
This program copies two ranges from stops using slice() and prints each copy. The output shows the middle and tail stops.
middle contains positions 1 and 2, while tail contains everything from position 2 onward. The end position is excluded, just as it was with string slice().
Editing a Slice Without Changing the Source
The range from slice() is a separate array, so we can change one of its values without changing stops. This differs from the earlier lesson on shared arrays, where assigning an array to another variable gave both variables a reference to the same array. Here, slice() creates a separate array containing the same strings. Changing a position in this new array leaves the source array unchanged.
This program changes one value in the copied middle array and prints both arrays. The output shows that only the copy changed.
Only middle changed. The original still contains all four stops, including "Museum" at position 1. This is a useful way to work with a range while keeping the source list intact.
