Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript typedArray.copyWithin() with Examples

Improve Article
Save Article
  • Last Updated : 22 Dec, 2022
Improve Article
Save Article

The Javascript typedArray.copyWithin() is an inbuilt function in JavaScript that is used to copy some elements of a typedArray at the specified location in the same typedArray. 

Syntax:

typedArray.copyWithin(target, start, end)

Parameters: It accepts three parameters that are specified below-

  • target: It is the start index position from where to copy the element.
  • start: It is the start index position from where to start copying elements and its default value is starting index of the typedArray.
  • end: It is optional and it is the end position index till the elements are to be copied and its default value is the end of the typedArray.

Return value: It returns the modified array after the copying process is done.

JavaScript examples to show the working of this function:

Example 1: This example shows the use of typedArray.copyWithin() function with all parameters.

javascript




<script>
    // Constructing a new typedArray "A"
    // with some elements
    const A = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
      
    // Calling copyWithin function to copy
    // element from index position 0 and
    // element from index 4 to 5
    A.copyWithin(0, 4, 5);
      
    // Printing a new modified array
    console.log(A);
</script>

Output:

25,10,15,20,25,30,35,40

Example 2: This example shows the use of typedArray.copyWithin() function with all parameters.

javascript




<script>
    // Constructing some new typedArrays
    // with some elements
    const A = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const B = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const C = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const D = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const E = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
      
    // Calling copyWithin function with different
    // parameters
    a = A.copyWithin(0, 5);
    b = B.copyWithin(1, 4);
    c = C.copyWithin(0, 4, 5);
    d = D.copyWithin(2, 3, 5);
    e = E.copyWithin(0, 1, 4);
      
    // Printing new modified arrays
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);
    console.log(e);
</script>

Output:

30,35,40,20,25,30,35,40
5,25,30,35,40,30,35,40
25,10,15,20,25,30,35,40
5,10,20,25,25,30,35,40
10,15,20,20,25,30,35,40

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!