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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay