Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 50

Shallow Copies with Slice

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Welcome back.

In our last lesson, we explored how to add and remove elements from the ends of an array using push, pop, shift, and unshift. A key characteristic of those methods is that they all mutate, or change, the original array.

Today, we'll learn about a method that works differently: slice(). The slice() method is incredibly useful because it is non-destructive—it returns a new array without changing the original. Our main focus will be on how to use slice() to create a copy of an array, a fundamental operation in modern JavaScript. This will also lead us into the important concept of "shallow copies," which is a key piece of "under the hood" knowledge for understanding how JavaScript handles data.

By the end of this lesson, you'll be able to use slice() to create a safe copy of an array, protecting your original data from unintended changes.

The Problem: Copying by Reference

Before we dive into slice(), let's quickly revisit a core concept from Module 2: primitive vs. reference types. Arrays are reference types. This means when you try to "copy" an array using the assignment operator (=), you aren't creating a new array. You're just creating a second variable that points to the exact same array in memory.

let originalFruits = ['Apple', 'Orange'];

// This does NOT create a new array
let copiedFruits = originalFruits; 

// Let's modify the 'copy'
copiedFruits.push('Banana');

// Now check the original...
console.log(originalFruits); // Output: ['Apple', 'Orange', 'Banana'] 

As you can see, changing copiedFruits also changed originalFruits! This happens because both variables point to the same location in memory. This is often not what we want. We need a way to create a true, independent copy.


Creating Copies and Extracts with slice()

The slice() method provides a solution. It "slices" a piece out of an array and gives you a new array containing that piece. The original array is left completely untouched.

The basic syntax is array.slice(startIndex, endIndex).

  • startIndex: The index where the slice begins.
  • endIndex: The index before which the slice ends. The element at endIndex is not included.

If you omit the endIndex, the slice goes to the end of thearray.

Understanding JavaScript Array slice() Method
This image shows how `fruits.slice(2, 4)` extracts a new array containing the elements from index 2 up to (but not including) index 4 from the original `fruits` array.

The most common use case for our purpose today is calling slice() with no arguments at all. When you do this, it copies the entire array from start to finish, giving you a new, independent array.

let originalHobbies = ['Sports', 'Cooking'];

// Create a REAL copy using slice()
let newHobbies = originalHobbies.slice();

// Now, modify the new array
newHobbies.push('Reading');

console.log(originalHobbies); // Output: ['Sports', 'Cooking']
console.log(newHobbies);      // Output: ['Sports', 'Cooking', 'Reading']

Success! By using originalHobbies.slice(), we created a true copy. Modifying newHobbies did not affect originalHobbies.

For a great video walkthrough of slice() in action, please watch the following tutorial.

slice Array Method | JavaScript Tutorial

This video from Florin Pop's channel provides a clear, concise tutorial on the slice method, covering its various uses.

Watch from the beginning to 01:27. Pay attention to how slice can be used to extract a portion of an array and, importantly, how calling it with no arguments creates a complete copy. Notice the emphasis on the fact that the original array is not modified.


The "Why": Understanding Shallow Copies

You've successfully created a copy, but there's an important detail to understand. slice() performs what is known as a shallow copy. This is a critical concept, especially for your goal of learning Next.js, where principles of data immutability are common.

To understand this, let's use a simple analogy.

Shallow Copy vs Deep Copy in JavaScript (Explained Like ...

The article 'Shallow Copy vs Deep Copy in JavaScript' uses a great pizza analogy to explain this concept. It's a very intuitive way to grasp the difference.

Read the section titled 'The Pizza Analogy (So Simple You’ll Never Forget)'. This will give you a simple mental model for shallow vs. deep copies.

A shallow copy means that only the top-level elements of the array are copied.

  • If the elements are primitive types (like numbers or strings), their values are copied directly into the new array.
  • However, if the elements are reference types (like objects or other arrays), only the references (the pointers to the memory location) are copied, not the objects themselves.
Shallow Copy vs. Deep Copy Illustration
This diagram shows the core difference. In a shallow copy, the original and the copy both point to the same referenced object. In a deep copy, each has its own independent object.

Let's see this in action. The same article explains this "trap".

Shallow Copy vs Deep Copy in JavaScript (Explained Like ...

Now let's see how a shallow copy behaves with nested objects. This is the crucial part that defines a 'shallow' copy.

Read the section 'Real Shallow Copy Methods in JavaScript'. Focus on the 'Array shallow copies' part and the example with the user object. Note how arr.slice() is listed as a method for shallow copying. The key takeaway is how changing a nested array (shallowCopy.hobbies.push) affects the original object.

Here's the code from that article, which perfectly illustrates the point:

const user = {
    name: "Ankit",
    hobbies: ["coding", "gaming"],
};

// Let's create an array with this user object
const users = [user];

// Now, create a shallow copy of the array
const shallowCopyOfUsers = users.slice();

// Let's modify the hobbies of the user in the *copied* array
shallowCopyOfUsers[0].hobbies.push("fitness");

// Check the hobbies of the user in the *original* array
console.log(users[0].hobbies); 
// Output: ["coding", "gaming", "fitness"] 😱

Even though users and shallowCopyOfUsers are two different arrays, the user object inside them is the same single object in memory. Changing it in one place changes it everywhere it's referenced.

For now, slice() and its shallow copy behavior are all you need. Creating "deep copies" is a more advanced topic, but being aware of the distinction is a huge step forward.

Test your understanding!

You have an array representing a list of products.

let products = ['Keyboard', 'Mouse', 'Monitor'];

You want to create a promotional list that adds a "SALE" tag to each product, but you must not change the original products array.

  1. Create a new array, promoProducts, that is a safe copy of the products array.
  2. Using a for loop, iterate over promoProducts and append the string " (SALE)" to each element.
  3. Log both products and promoProducts to the console to verify that the original array was not changed.
Show answer
let products = ['Keyboard', 'Mouse', 'Monitor'];

// 1. Create a safe copy
let promoProducts = products.slice();

// 2. Modify the copy
for (let i = 0; i < promoProducts.length; i++) {
    promoProducts[i] = promoProducts[i] + ' (SALE)';
}

// 3. Verify the results
console.log(products);       // Expected output: ['Keyboard', 'Mouse', 'Monitor']
console.log(promoProducts);  // Expected output: ['Keyboard (SALE)', 'Mouse (SALE)', 'Monitor (SALE)']

Explanation: By using products.slice(), we created a new array promoProducts. The loop then modified this new array. The original products array remained untouched because the two arrays are independent entities in memory.


Practical Use Case: Copying Before Sorting

A very common reason to copy an array is when you need to sort it but also need to preserve the original order. The sort() method, which we will see in more detail later, modifies the array in place. To avoid this, you can slice() it first!

The following article demonstrates this exact pattern.

Array methods

The 'Array methods' article on javascript.info provides a perfect example of why you'd want to copy an array before modifying it.

Find the heading 'Copy and sort array'. Look at the copySorted function. This is a very common and useful pattern in JavaScript: arr.slice().sort(). It chains the methods together to first create a copy, then sort that copy, all in one line.

This pattern, array.slice().sort(), is elegant and efficient. It clearly communicates the intent: "I want a sorted version of this array, but don't touch the original."


Conclusion

Today you've added a subtle but powerful tool to your array toolkit. You've learned how slice() can be used to create copies of arrays, protecting your original data from modification.

Key Takeaways:

  • Assigning an array with = only copies the reference, not the array itself.
  • array.slice() creates a new array, providing a shallow copy of the original.
  • A shallow copy means that while the top-level array is new, any nested objects or arrays inside it are still shared references.
  • A common and important pattern is to use slice() to create a copy before performing a destructive operation like sorting, preserving the original data.

Next Up

The slice() method is your go-to for non-destructively extracting parts of an array or making a copy. In the next lesson, we will look at its similarly named but very different cousin: splice(). Be careful not to confuse them! While slice() reads data without changing it, splice() is a powerful tool for modifying an array by adding, removing, or replacing elements at any position.