JavaScript slice(): Array and String Examples

Learn JavaScript slice() for arrays and strings, including start/end indexes, negative indexes, shallow copy behavior, and slice vs splice.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript slice(): Array and String Examples

slice() extracts part of an array or string and returns a new value. It does not modify the original array or string. This makes slice() useful when you need a copy, a subset, or a safe non-mutating operation.

For arrays, use array.slice(start, end). For strings, use string.slice(start, end). The end index is not included.

Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).


Method 1: Slice an Array by Start and End Index

javascript
const nums = [10, 20, 30, 40];

console.log("slice-array:", nums.slice(1, 3).join(","));
Output

You should see one line logging slice-array: 20,30.

Index 1 is included. Index 3 is excluded.


Method 2: Use Negative Indexes

javascript
const nums = [10, 20, 30, 40];

console.log("slice-negative:", nums.slice(-2).join(","));
Output

You should see one line logging slice-negative: 30,40.

Negative indexes count from the end of the array.


Method 3: Confirm slice Does Not Mutate

javascript
const nums = [10, 20, 30, 40];
nums.slice(1, 3);

console.log("slice-original:", nums.join(","));
Output

You should see one line logging slice-original: 10,20,30,40.

Use splice() instead when you intentionally want to change the original array.


Method 4: Slice a String

javascript
console.log("slice-string:", "JavaScript".slice(0, 4));
Output

You should see one line logging slice-string: Java.

String slice() returns a substring and leaves the original string unchanged.


Common Questions About JavaScript slice

Does slice modify the original array?

No. slice() returns a new array or string section and keeps the original value unchanged.

What is the difference between slice and splice?

slice() copies part of an array. splice() changes the original array by removing, replacing, or adding items.

Is the end index included in slice?

No. The end index is excluded.


Summary

Use JavaScript slice() when you need a non-mutating subset of an array or string. It accepts start and end indexes, supports negative indexes, excludes the end index, and keeps the original value unchanged.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …