DevelopmentJavaScript | 5 Min Read

JavaScript Array Methods: Array.prototype.copyWithin() Explained

The Array is one of the most important data types in JavaScript, here is everything you need to know about the Array method Array.prototype.copyWithin().

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[1, 2, 3, 4, 5, 6].copyWithin(-4); // [1,2,1,2,3,4]
jsx

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.

11,2,3,4,5,6 // array values
20 1 2 3 4 5 // positive array indexes
3-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[1, 2, 3, 4, 5, 6][(1, 2, 3, 4, 5, 6)];
jsx

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.

1arr.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

1// only passing the target parameter
2[1, 2, 3, 4, 5, 6].copyWithin(-4); // [1,2,1,2,3,4]
3
4// passing both the target and the start parameters
5[1, 2, 3, 4, 5, 6].copyWithin(-4, 4); // [ 1, 2, 5, 6, 5, 6 ]
6
7// passing all parameters
8[1, 2, 3, 4, 5, 6].copyWithin(2, 3, 5); // [ 1, 2, 4, 5, 5, 6 ]
9
10// using .copyWithin with nested arrays
11[1, 2, [3], [1], 4]
12 .copyWithin(2, -4) // [ 1, 2, 2, [3], [1] ]
13
14 [
15 // using .copyWithin with empty nested items
16 ([], {}, 1, 2)
17 ].copyWithin(2, 0, 2); // [ [], {}, [], {} ]
jsx

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:

1const arr1 = [1, 2, 3, [4]];
2const arr2 = arr1.copyWithin(0, -1);
3
4arr1[3].push(2);
5
6console.log(arr2);
7
8// Question: What will arr2 be equal to when logged?
jsx

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



Content

Latest Blog Posts

Below is my latest blog post and a link to all of my posts.

View All Posts

Content

Latest Video

Here is my YouTube Channel and latest video for your enjoyment.

View All Videos
AWS Bedrock Text and Image Generation Tutorial (AWS SDK)

AWS Bedrock Text and Image Generation Tutorial (AWS SDK)

Contact

Join My Newsletter

Subscribe to my weekly newsletter by filling in the form.

Get my latest content every week and 0 spam!