JavaScript Array Methods: Array.prototype.copyWithin()

03/06/2020 | 3 minute read | Languages: JavaScript,

Series Introduction

The JavaScript Array data type currently has 37 methods on it according to the MDN docs and in this series we are going to cover them all one by one explaining each with examples as we work our way down the list.

If you have any questions regarding anything in this series please get in contact with me by using the methods listed at the bottom of this post and if you think I've got something wrong please create a pull request on GitHub to correct the information (link at the bottom of the article).

This is post #5 in the series. If you're interested in reading any of the other posts in this series, there is a up-to-date list at the bottom of this post.


Method #5: Array.prototype.copyWithin()

.copyWithin() allows for the shallow copying of part of the array the method was called on to another location within the same array. After completing it's actions it will then return a modified version of this array without any modifications to it's length.

In practice what this means is you can copy any part of an array to another location within the same array without modifying the length of it. That final part is important because if .copyWithin() allowed for the modification of the array length we could be inadvertently increasing the length of the array every time we call the method which could create a whole host of errors and bugs.

For a simple example:

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

Let's work out what is going on here.

We will cover the syntax of this method in a second but the argument we are passing to the method in this example is the location of where we want to begin pasting in the copied values from and because we haven't specified a start and end point it takes the entire array as the values to be copied.

Below is a simple diagram of positive and negative indexes for an array, this is important as negative indexes can play a big role when using this method.

1,2,3,4,5,6 // array values
0 1 2 3 4 5 // positive array indexes
-6 -5 -2 -3 -2 -1 // negative array indexes

Using the above diagram you can see that we took all of the values from the array, copied them and then moved the copy forward until the first value was then at the index we specified for the target which was -4. So, to visualize what we have done here it would be:

[1, 2, 3, 4, 5, 6]
      [1, 2, 3, 4, 5, 6]

Now, this is why it's important that the method doesn't modify the length of either array, if it did then in this example the returned array would become: [1, 2, 1, 2, 3, 4, 5, 6] or two indexes longer than the array we started with.

Syntax

Let's take a look at the syntax for this method before moving on and looking at some more examples.

arr.copyWithin(target[, start[, end]])

.copyWithin() takes in a total of 3 parameters, these are:

  • target: The index of the value we want to start the copied array from, this can be either positive or negative, if negative then it will count from the end of the array. If a value greater than the length of the array is provided then nothing is copied and the original array is returned. Finally, similar to the example above, if the target parameter value is after the start parameter value then the copied array will be copied to the new location and trimmed to fit within the array.length.
  • Optional | start: The start parameter allows us to specify where we wish to begin copying the array from. This is based on the zero index of the array and if provided with a negative index then will start counting from the end of the array. If no value is provided here then it will take index 0 as the default value.
  • Optional | end: The end parameter allows us to specify the end index of the array to be copied and if omitted the default value used is the last index of the array which is by default the value equal to array.length. When using the end parameter, copyWithin will copy all values up to but not including the index provided.

Return: .copyWithin returns the modified array to us.

Let's take a look at some examples of this method in use:

Examples

// only passing the target parameter
[1,2,3,4,5,6].copyWithin(-4); // [1,2,1,2,3,4] 

// passing both the target and the start parameters
[1,2,3,4,5,6].copyWithin(-4, 4); // [ 1, 2, 5, 6, 5, 6 ]

// passing all parameters
[1,2,3,4,5,6].copyWithin(2, 3, 5); // [ 1, 2, 4, 5, 5, 6 ]

// using .copyWithin with nested arrays
[1,2,[3],[1],4].copyWithin(2, -4) // [ 1, 2, 2, [3], [1] ]

// using .copyWithin with empty nested items
[[], {},1 ,2].copyWithin(2,0,2) // [ [], {}, [], {} ]

Hopefully, you know have a better understanding of this method because I'm going to issue you with a coding question based on it. The first person to tweet me on Twitter (@MrConerMurphy) with the correct answer will be shouted out and pinned to my Twitter for 24 hours. So, the pressure is on. 🔥

Here, is your question:

const arr1 = [1,2,3,[4]];
const arr2 = arr1.copyWithin(0, -1);

arr1[3].push(2);

console.log(arr2); 

// Question: What will arr2 be equal to when logged?

I look forward to hearing your answers over on Twitter and if you have any questions for me, I would be happy to answer them for you; please get in touch via one of the links below.

See you in the next post. 😃

Series post links

,

Want More Content?

Join my weekly newsletter below.

Don't worry, I won't send you spam and you can unsubscribe at any time.