.copyWithin()
The .copyWithin()
method returns a shallow copy of an array where one subarray replaces another part without modifying the original length. However, since it is a mutating method, .copyWithin()
will change the array’s contents and create or delete properties if necessary.
Syntax
myArray.copyWithin(target);
myArray.copyWithin(target, start);
myArray.copyWithin(target, start, end);
The following parameters can be applied to the .copyWithin()
method:
target
(required): A zero-based index to copy the sequence to.- If
target
is negative, it counts back frommyArray.length
andtarget + myArray.length
is used. - If
target
is <myArray.length * -1
,0
is used. - If
target
is >=myArray.length
, nothing is copied. - If, after
myArray
is normalized, thetarget
is positioned afterstart
, copying only occurs until the end ofmyArray.length
(i.e.,.copyWithin()
never extends themyArray
).
- If
start
(optional): A zero-based index at which to start copying the elements from.- If
start
is negative, it counts back from the end ofmyArray
andstart + myArray.length
is used. - If
start
<myArray.length * -1
or it is omitted,0
is used. - If
start
>=myArray.length
, nothing is copied.
- If
end
(optional): A zero-based index at which to end copying elements from (non-inclusive).- If
end
is negative, it counts back from the end ofmyArray
andend + myArray.length
is used. - If
end
<myArray.length * -1
,0
is used. - If
end
>=myArray.length
or it is omitted,myArray.length
is used and all elements until the end are copied. - If
end
is positioned before or atstart
after normalization, nothing is copied.
- If
Sparse Arrays
If the .copyWithin()
method is applied to a sparse array that contains empty slots, it will populate them with an undefined
value:
console.log([1, , 3].copyWithin(2, 1, 2));// Output: [1, undefined, undefined]
Example
The following examples has a few calls to the .copyWithin()
method, applying combinations of the available parameters:
// copy elements starting from the second-to-last indexconsole.log([1, 2, 3, 4, 5].copyWithin(-2));// copy to index 0 all elements index 3 to the endconsole.log([1, 2, 3, 4, 5].copyWithin(0, 3));// copy to index 0 the element at index 2console.log([1, 2, 3, 4, 5].copyWithin(0, 2, 3));// copy to second-to-last index elements starting from index 2 until end of arrayconsole.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
This will produce the following output:
[ 1, 2, 3, 1, 2 ][ 4, 5, 3, 4, 5 ][ 3, 2, 3, 4, 5 ][ 1, 2, 3, 3, 4 ]
Codebyte Example
The following example uses the .copyWithin()
method to copy the second element at index 1 (‘b’) to the fourth element at index 3:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.