JS-060
Visual JavaScript guide to slice(): Learn to copy part of an array using slice()
Beginner5 min~5 min read#array#slice#copy

slice()

Copy part of an array

Goal

Learn to copy part of an array using slice().

Explanation

  • slice() creates a new array from part of an existing array.
  • The original array does not change.
  • The first argument specifies the starting index.
  • The second argument specifies the index at which copying stops.
  • The ending index is not included in the result.

Analogy

Imagine a loaf of bread. You cut off a few slices for yourself, but the original loaf remains intact.

Code

const fruits = [
  "Apple",
  "Banana",
  "Orange",
  "Kiwi"
];

console.log(fruits.slice(1, 3));

Result: ["Banana", "Orange"]

Common mistake

Beginners often think slice(1, 3) includes the element at index 3. In fact, it copies only up to that index.

Remember

  • slice() creates a new array.
  • The original array does not change.
  • The ending index is not included.

Quick Quiz

What does ["A", "B", "C", "D"].slice(1, 3) return?

Resources