Basics of Javascript · Array · copyWithin() (method)

Jakub Korch
Nerd For Tech
Published in
5 min readDec 12, 2023

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Hi there dev newbs! I have prepared yet another Array object method for you to present to. This time, it will be a method which allows you to copy parts of an array inside of itself. How exciting!

The method copyWithin() shallow copies part of the array to another location in the same array and returns this array without modifying its length. The first argument is always target position, the second parameter is position to start copying elements from and optional third parameter is an end position for copying. The start position is inclusive and the end position is exclusive. It might be confusing, so let’s see it in action in the first example.

// Example 1
// basic usage

console.log("EXAMPLE 1");
console.log("--------------------------------------------------");

let letters = ["a", "b", "c", "d", "e", "f"];

// copy the elements starting at index 4 until end to index 0 and so on
console.log(letters.copyWithin(0,4));
// returns ['e', 'f', 'c', 'd', 'e', 'f']

letters = ["a", "b", "c", "d", "e", "f"];

// copy the element from index 3 to index 0
console.log(letters.copyWithin(1,2,5));
// returns ['a', 'c', 'd', 'e', 'e', 'f']

First expression shows us the case, where only two arguments are provided. The part of the array starting at the start position up to the last element is being copied into the positions starting at the target index and going forward until all the elements are placed. In our case it takes the elements from positions 4 and 5 and copies the values into the position 0 and 1 respectively.

Second expression handles the case when the range for copying is specified exactly. In our case the elements to be copied are at the positions 3 and 4, excluding 5 and they are copied into position starting at index 0 going forward until all elements are placed.

Similarly, like method at(), the method copyWithin() is capable of handling negative indexes for any of the three available arguments. However, there are still limitations to the index values. Following rules apply to all the three arguments:

  • if argument < 0, then argument + array.length is used
  • if argument < -array.length, then 0 is used
  • if argument >= array.length, then nothing is copied

On top of this common conditions, specific arguments have their own extra conditions:

  • if target > start (after normalization), copying only happens until the end of array.length
  • if end >= array.length or is omitted, then array.length is used
  • if end < start (after normalization), then nothing is copied

Let’s see this situations in practical examples to understand it better.

// Example 2
// negative arguments + edge cases

console.log("EXAMPLE 2");
console.log("--------------------------------------------------");

let animals= ["bear", "rabbit", "fox", "eagle", "owl", "sparrow", "crow"];

// negative start / end / target
console.log(animals.copyWithin(-2,-5,-3));
// returns ['bear', 'rabbit', 'fox', 'eagle', 'owl', 'fox', 'eagle']

// reset the array
animals = ["bear", "rabbit", "fox", "eagle", "owl", "sparrow", "crow"];

// target > start
console.log(animals.copyWithin(4, 2));
// returns ['bear', 'rabbit', 'fox', 'eagle', 'fox', 'eagle', 'owl']

// reset the array
animals = ["bear", "rabbit", "fox", "eagle", "owl", "sparrow", "crow"];

// end >= array.length
console.log(animals.copyWithin(2, 5, 8));
// returns ['bear', 'rabbit', 'sparrow', 'crow', 'owl', 'sparrow', 'crow']

// reset the array
animals = ["bear", "rabbit", "fox", "eagle", "owl", "sparrow", "crow"];

// end < start
console.log(animals.copyWithin(3, 5, 2));
// returns ['bear', 'rabbit', 'fox', 'eagle', 'owl', 'sparrow', 'crow']

Wow! This was quite an example block. So let’s unpack it one section at a time. Please pay attention to the fact that we had to reset the array after each use, because this method actually modifies the original array.

In the first section, we are using all the negative indexes, which are then internally normalized by adding the value of array.length to each one of them. We then end up with the values 5 for the target, 2 for the start and 4 for the end. If you try this combination, you will end up with the exact same result.

The second section handles the case when the target is greater than start, which results in the copying only happening until the end of array.length.

The third section deals with the case when the end value is greater than or equal to length of the array, which results in the end being assigned the value of array’s length. Again, from the comparison of the results when using end equal to array length, we would see that results are identical.

The last section showcases the situation when the end is less than the start which results in the array being untouched. Everything stays as was in the array before the execution of the method.

The next section shows how the method handles sparse arrays.

// Example 3
// sparse arrays

console.log("EXAMPLE 3");
console.log("--------------------------------------------------");

let numbers = [1,2,,,5,6,7,,9,10];

// sparse arrays no end
console.log(numbers.copyWithin(5,-3));
// returns [1, 2, empty, empty, 5, empty, 9, 10, 9, 10]

// reset the array
numbers = [1,2,,,5,6,7,,9,10];

// sparse arrays with end
console.log(numbers.copyWithin(2,-2,10));
// returns [1, 2, 9, 10, 5, 6, 7, empty, 9, 10]

The first example tries to copy the last three elements from an array to the position starting at index 5. Values empty, 9 and 10 are successfully copied into positions with indexes 5, 6 and 7.

In the second example, the target index starts at position 2 and we are trying to copy items from the end, starting with the second from the end. Pay attention to the fact that the only way to include also the last element from the array, is to use the value of array length as end value. The only other option would be to omit it completely.

As with many other methods, we can use method copyWithin() also with objects that are only array-like. Let’s see it in action.

// Example 4
// array-like objects use

console.log("EXAMPLE 4");
console.log("--------------------------------------------------");

let arrLikeObj = {
length: 4,
0: "x",
2: "a"
}

console.log(Array.prototype.copyWithin.call(arrLikeObj, 0, 2));
// returns {0: 'a', 2: 'a', length: 4}

// reset array-like object
arrLikeObj = {
length: 4,
0: "x",
2: "a"
}

console.log(Array.prototype.copyWithin.call(arrLikeObj, 1, 2 , 3));
// returns {0: 'x', 1: 'a', 2: 'a', length: 4}

The first situation tries to copy values “a” at position 2 and empty at position 3 to position starting at index 0, overwriting value “x” there and empty value at index 1 with the same empty value.

The second situation simulates the situation where value “a” from the position 2 is copied at position 1 which is currently empty and therefore is changed to value “a”.

Do not let yourself be confused with the fact that empty values are not listed. They are there.

Okay, that is all for today. I don’t know about you, but this one was quite a challenge. My head is still on fire even now after we finished. Take it easy and see you soon with the next method.

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Jakub Korch
Jakub Korch

Written by Jakub Korch

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.

No responses yet