What does the JavaScript Array copyWithin() method do?

Hey, what’s up JavaScript learners. Javascript has so many Array methods and one of them is the method copyWithin(), the method about which we are going to talk about in this post. So without further ado let’s get straight into our topic.

So first let’s see What is the JavaScript Array copyWithin() method?

The JavaScript Array copyWithin() method does exactly what its name says. Its name is copyWithin, which itself says, it will copy elements within the same array.

So, you use this method when you have to copy parts of an array to another location in the same array.

This method overwrites the existing values and returns the modified array.

Now let’s see the syntax of the JavaScript array copyWithin() method.

array.copyWithin(target, start, end)

Let me explain the parameters that the JavaScript arrayWithin() method takes.

target – This is the index at which you want to copy the elements to. This is the required parameter.

start – This is the index from which you want to start copying the elements. This is an optional parameter. If you don’t specify this parameter the method will copy the elements from the index 0.

end – This is also an optional parameter. By specifying this parameter you are telling the method from where to stop copying the elements. The end index is exclusive. If you are specifying end index 6 then the method will copy until the index 5. If you don’t specify this parameter then the copyWithin() method will copy till the last index.

Now if you find the parameters confusing then here’s a trick to memorize them.

Consider the target as a shooting target. Now you are telling the method to take the bullets(elements from the start to end-1 index) and shoot the target(start copying).

Now it’s time to see an example.

Example –

<!DOCTYPE html>
<html>
<body>

<h1>The JavaScript Array copyWithin() Method</h1>

<p id="demoId"></p>

<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar", "Ford", "Tesla"];

document.getElementById("demoId").innerHTML = cars.copyWithin(3,0,2);
</script>

</body>
</html>

Output :

The JavaScript Array copyWithin() Method

Porsche,BMW,Audi,Porsche,BMW,Tesla

Notice the parameter of copyWithin() method. I have passed the index 3 as the target index, 0 as the start index and 2 as the end index.

So, the method will work like that – It will copy elements from index 0 to index 1 (As I mentioned earlier that the end index is exclusive) and start putting these elements starting from the 3rd index. And then returns the modified array.

And this ends the post here.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: