JavaScript Array copyWithin() Method Example

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

The Array.copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

Syntax

array.copyWithin(target, start, end)
  • target(Required) - The index position to copy the elements to
  • start (Optional) - The index position to start copying elements from (default is 0)
  • end (Optional) - The index position to stop copying elements from (default is array.length)

Examples

Example 1: Copy the first two array elements to the last two array elements

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
output
["Banana", "Orange", "Banana", "Orange"]

Example 2: Copy the first two array elements to the third and fourth position

var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
fruits.copyWithin(2, 0, 2);
Output:
["Banana", "Orange", "Banana", "Orange", "Kiwi", "Papaya"]

More Examples

[1, 2, 3, 4, 5].copyWithin(-2);
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// On platforms that are not yet ES2015 compliant: 
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare