TypeScript Array slice()
Syntax & Examples
Array.slice() method
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
Syntax of Array.slice()
The syntax of Array.slice() method is:
slice(start?: number, end?: number): T[]
This slice() method of Array returns a section of an array.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | optional | Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the sequence. If start is undefined, slice starts from the index 0. |
end | optional | Zero-based index before which to end extraction. slice extracts up to but not including end. A negative index can be used, indicating an offset from the end of the sequence. If end is omitted, slice extracts through the end of the sequence (arr.length). |
Return Type
Array.slice() returns value of type T[]
.
✐ Examples
1 Using slice() to extract a portion of an array
The slice() method can be used to extract a portion of an array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Use
slice(1, 3)
to extract a portion of the array. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const result = arr.slice(1, 3);
console.log(result);
Output
[2, 3]
2 Using slice() with a negative start index
The slice() method can be used with a negative start index to extract a portion of an array from the end.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Use
slice(-3)
to extract the last three elements of the array. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const result = arr.slice(-3);
console.log(result);
Output
[3, 4, 5]
3 Using slice() with no arguments
The slice() method can be used without arguments to create a shallow copy of the entire array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Use
slice()
to create a shallow copy of the array. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const result = arr.slice();
console.log(result);
Output
[1, 2, 3, 4, 5]
Summary
In this TypeScript tutorial, we learned about slice() method of Array: the syntax and few working examples with output and detailed explanation for each example.