Open In App

TypeScript Array.prototype.copyWithin() Method

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The copyWithin() method is available in the TypeScript Array.prototype it helps you to rearrange the elements within the array by copying a sequence of array elements. This method is good for tasks such as shifting elements, removing them without creating gaps, or copying portions of arrays.

Syntax

array.copyWithin(target, start, end)

Parameters:

  • target: It contains the index position from which the copying of elements will start.
  • start (optional): It contains the index position of the first element to copy (defaults to 0).
  • end (optional): It contains the index position of the last element to copy (excluding it) (defaults to the array’s length).

Return Value:

This method returns the same array instance (not a new array), allowing for chaining.

Example 1: The below example is the basic implementation of copyWithin() method with two parameters.

Javascript




const geeks: string[] =
    ['GFG', 'JavaScript', 'GFG', 'TypeScript'];
 
// Copying the element at 3rd position and
// store it at position 1
geeks.copyWithin(1, 3);
console.log(geeks);


Output:

["GFG", "TypeScript", "GFG", "TypeScript"]

Example 2: The below code implements the copyWithin() method with three parameters.

Javascript




const geeks: string[] =
    ['JavaScript', 'TypeScript', 'GeeksforGeeks', 'GFG'];
 
// Copying the elements stored between position
// 1(inclusive) and 3(exclusive) and then store
// them at position 2
geeks.copyWithin(2, 1, 3);
console.log(geeks);


Output:

["JavaScript", "TypeScript", "TypeScript", "GeeksforGeeks"]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads