An idiomatic way to create shallow copies of arrays uses slice.
const originalArr = [1,2,3]; const copy = originalArr.slice();
This post dives into the slice method and describes a few more tips and tricks. At the end of this post you should know the output of [1,2,3].slice(-3,-1).
Slice
The full method signature is arr.slice(start, end). Start and end are optional parameters defaulting to 0 and arr.length respectively.
start: The zero-based index to start the copy from; defaults to 0 if not specified.
end: The index to copy up to, the last copied element will be the element located at end – 1. Defaults to arr.length if not specified.
Return
Slice will return a new array with the copied elements.
Usage
1. Cloning arrays
const originalArr = [1,2,3]; const copy = originalArr.slice(); // [1,2,3]
The code above is similar to the one below (with defaults set)
const copy = originalArr.slice(0, 3); // [1,2,3]
2. Copy all values starting from some index
const originalArr = [1,2,3,4,5,6]; const copy = originalArr.slice(3); // [4, 5, 6]
3. Copy a subsection of an array
const originalArr = [1,2,3,4,5,6]; const copy = originalArr.slice(3,5); // [4, 5]
Test your knowledge
What will be the output of the code below?
Hint: The element at the end index is not included in the copy operation.
const originalArr = [1,2,3,4,5,6]; const copy = originalArr.slice(3,4);
const originalArr = [1,2,3]; const copy = originalArr.slice(0, 200);
const originalArr = [1,2,3]; const copy = originalArr.slice(5, 200);
Mastery requires familiarity with both the mundane and esoteric.
let originalArr = [1,2,3]; let copy = originalArr.slice(-1); // [2] // start is -1; this is equivalent to a start value of 2 // equivalent code: originalArr.slice(2); // Negative start and end originalArr = [1,2,3]; copy = originalArr.slice(-2,-1); // [2] // start is -1; this is equivalent to a start value of 2 // end is -2; this is equivalent to a start value of 3 // equivalent code: originalArr.slice(2,3);
That’s about it! Now go pull slice tricks on your friends and show off your JavaScript slicing superpowers.