DEV Community

Cover image for JavaScript - copyWithin() Method
Kristiyan Velkov
Kristiyan Velkov

Posted on

1 1 1 1 1

JavaScript - copyWithin() Method

The copyWithin() method allows you to copy a sequence of elements within an array to another position within the same array. It modifies the original array in place and returns a reference to the modified array.


The syntax for copyWithin() is as follows:

array.copyWithin(target, start, end)
Enter fullscreen mode Exit fullscreen mode
  • target: The index at which to copy the elements to. It can be a positive or negative number. If it is negative, it will be counted from the end of the array. If the target index is greater than or equal to the length of the array, no elements will be copied.

  • start: The index at which to start copying elements from. It is optional and defaults to 0 if not provided. If it is negative, it will be counted from the end of the array.

  • end: The index at which to stop copying elements from. It is optional and defaults to the length of the array if not provided. If it is negative, it will be counted from the end of the array.


Example:

const array = [1, 2, 3, 4, 5];

// Copy elements starting from index 3 to index 0
array.copyWithin(0, 3);
console.log(array); // Output: [4, 5, 3, 4, 5]

// Copy elements starting from index 1 to index 3
array.copyWithin(3, 1, 2);
console.log(array); // Output: [4, 5, 3, 5, 5]
Enter fullscreen mode Exit fullscreen mode

Browser compatibility

Image description


Image description

linkedin


Image description

If you like my work and want to support me to work hard, please donate via:

Revolut website payment or use the QR code above.

Thanks a bunch for supporting me! It means a LOT 😍

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay