JavaScript's copyWithin is strange ๐Ÿ˜ฌ

JavaScript's copyWithin is strange ๐Ÿ˜ฌ

ยท

2 min read

I've been writing a comprehensive guide for JavaScript array methods while learning them myself. I tried out all possible variations of each method and the methods were doing what I expected them to do, except for one.

I spent quite some time trying to wrap my head around the copyWithin method. Finally, I feel I've got the hang of it now.

Hey there, fellow human of the 'Not-Getting-It' realm! This article? Yep, not for the instant 'I-get-it' champs like you. This one's for us, the brave souls who embrace confusion like a warm hug. So, kick back, relax, and let's dive into the land of 'Huh? Wait, what?' together. Cheers to not getting it on the first try!

Usage

This method is used to copy a part of the given array and paste that copied content into another location in the same array

Syntax

copyWithin(target, start, end)

target (Required)- Where to paste the content to

start (Optional)- Where to start copying the content from (Default value - 0)

end (Optional)- Where to finish copying the content (Exclusive) (Default value - The length of the array)

Examples

// Example 1 - With only target parameter
let numbers = [90, 88, 33, 77, 5, 66]
numbers.copyWithin(2)
// The same as numbers.copyWithin(2, 0, 6)
console.log(numbers) // [ 90, 88, 90, 88, 33, 77 ]

This method,

  1. Copies the elements from indexes 0 to 6 (Exclusive), in this case, it is the whole array

  2. Then it pastes the copied content from index 2 onwards

// Example 2 - With start and end parameters
let numbers = [15, 18, 22, 40, 65, 35, 58]
numbers.copyWithin(2, 3, 6)
console.log(numbers) // [15, 18, 40, 65, 35, 35, 58]

// Example 3
let numbers = [15, 18, 22, 40, 65, 35, 58]
numbers.copyWithin(5, 3, 6)
console.log(numbers) // [15, 18, 22, 40, 65, 40, 65]

As you can see, this method never extends the array.

If there is not enough space to paste all the copied elements, it will just paste what it can and ignore the rest.

copyWithinis in the category of array modification methods. I will provide a comprehensive categorized guide for all the JS Array methods in an upcoming article.


Thank you for diving into the article! If you found it as captivating as a page-turner, consider dropping a virtual high-five with a like, leaving your thoughts in the comments, and embarking on a journey with me for more mind-enriching content. Until we cross paths again, take care and keep your curiosity alive! ๐Ÿš€โœจ

ย