Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript | typedArray.copyWithin() with Examples

  • Last Updated : 14 Feb, 2019

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

Syntax:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 to be copied and its default value is end of the typedArray.

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



    <>JavaScript code to show the working of this function:

    Code #1:




    <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
       document.write(A);
         
    </script>

    Output:

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

    Code #2:




    <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
       document.write(a +"<br>");
       document.write(b +"<br>");
       document.write(c +"<br>");
       document.write(d +"<br>");
       document.write(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
  • Recommended Articles
    Page :

    Start Your Coding Journey Now!