This page looks best with JavaScript enabled

Array `copyWithin` - what's the point?

 ·   ·  ☕ 2 min read

You must have seen the copyWithin() method for an array, and surely wondered what it can do. copywithin copies elements from one position to another position in the same array.

(Just kidding about the wondering thing - no one ‘wonders’ today, they just Google).

1
2
3
4
const fruits = ["apple", "orange", "grapes", "banana"];
fruits.copyWithin(2, 0, 2); // copy 2 ele from [0] to [2]
console.log("fruits: ", fruits);
// [ 'apple', 'orange', 'apple', 'orange' ]

copyWithin has the below syntax.

array.copyWithin(target, start, end)

It copies the elements from start to end to the target position.

The single biggest reason for you to use copyWithin is the speed. It is highly performant as compared to using array element assignment.

There are some interesting things here that may be worth your time -

  • Not specifying any parameters will just return the same array

  • Without the second parameter,

    1
    2
    3
    4
    
    const fruits = ["apple", "orange", "grapes", "banana"];
    fruits.copyWithin(1, 2); // copy 2 ele from [2] to [1]
    console.log("fruits: ", fruits);
    // [ 'apple', 'grapes', 'banana', 'banana' ]
    
  • Avoiding the second & third parameters will copy the first element to the specified position.

    1
    2
    3
    
    fruits.copyWithin(1); // copy 1 ele from [0] to [1]
    console.log("fruits: ", fruits);
    // [ 'apple', 'apple', 'orange', 'grapes' ]
    
  • You can have negative start and end to start from the end (i.e., length + start [or end])

    1
    2
    3
    4
    
    const fruits = ["apple", "orange", "grapes", "banana"];
    fruits.copyWithin(1, -1); // copy last ele to [1]
    console.log("fruits: ", fruits);
    // [ 'apple', 'banana', 'grapes', 'banana' ]
    

Despite the performance, I don’t think I will be using copyWithin any time soon. For the life of me I don’t recall a use case where I was copying elements from one position to the other in a single array.

But, that’s just me.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things