CodeBlanks Logo Icon CodeBlanks

splice and slice

Learn array slicing with .splice and .slice.

Modifying with splice

To remove or insert elements from the middle of an array you use .splice(start, deleteCount, ...items). start is the start index, deleteCount is how many to remove, items are the elements to insert.

For example const a = [1, 2, 3, 4]; a.splice(1, 2); removes 2 elements starting at index 1; a becomes [1, 4]. It returns the removed elements as an array. To insert, use the third argument: a.splice(1, 0, 9) inserts 9 at index 1, removing nothing. splice modifies the array in place.

Copying with slice

To take a part of an array as a copy you use .slice(start, end). start is the start index, end is the end index; end is excluded. The original array is not modified; a new array is returned.

For example const a = [1, 2, 3, 4]; const part = a.slice(1, 3); makes part equal to [2, 3]; a stays [1, 2, 3, 4]. slice also supports negative indices: a.slice(-2) returns the last two elements. Unlike splice, slice does not touch the array; this is why it is preferred when you want to keep the data intact while taking a part.

Practice Take a part with slice

The nums variable is set to [1, 2, 3, 4]. Declare a variable part and assign the result of nums.slice(1, 3) to it. Then print part[0] with console.log. The output on a single line must be 2.

Starter code

index.js
const nums = [1, 2, 3, 4];
// Declare part with slice(1, 3); print its first element

Sample solution

index.js
const nums = [1, 2, 3, 4];
const part = nums.slice(1, 3);
console.log(part[0]);

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the result of const a = [1, 2, 3, 4]; a.splice(1, 2);?

index.js
const a = [1, 2, 3, 4];
a.splice(1, 2);
  • a = [1, 4] Correct answer
  • a = [2, 3, 4]
  • a = [1, 2, 3, 4]
  • a = [1, 2]

Explanation: splice(1, 2) removes 2 elements from index 1; a becomes [1, 4].

2 Match each method to its job

Term Meaning
splice Modifies in place
slice Returns a copy part
push Appends at end
shift Removes from start

3 Write the slice call

Question
const a = [1, 2, 3, 4];
const part = a____(1, 3);
Answer
const a = [1, 2, 3, 4];
const part = a.slice(1, 3);

Explanation: .slice returns a copy of a part of the array.

All lessons in Beginner