Which Array Methods Change the Original Array in JavaScript?
Certain JavaScript array methods will mutate or modify the original array, and others don’t. There aren’t that many that do so, if possible, just memorize them.
Try this mnemonic: Chicken-Fried Suspicious Peppers. Actually, CF SUS PPRS.
copyWithin, fill, splice, unshift, shift, push, pop, reverse, sort
Here are the JavaScript methods that change the original array:
- Array.copyWithin(target, start, end) - copy part of your array to another part without changing the array length. Target is the only required argument. Returns the mutated array.
- Array.fill(value, start, end) - fill all or part of your array will a static value, the only required argument. Returns the mutated array.
- Array.splice(start, count, items) - remove, replace, or add one or more array items. Only start is required. Returns an array containing the deleted elements or an empty array, if none were deleted.
- Array.unshift(items) - adds one or more items to the beginning of the array. Returns numerical length of the mutated array.
- Array.shift() - removes the first array item. Returns the array item (value).
- Array.push(items) - adds one or more items to the end of the array. Returns numerical length of the mutated array.
- Array.pop() - removes the last array item. Returns the mutated array.
- Array.reverse() - reverses the order of array items. Returns the reversed array.
- Array.sort() - sorts the array items in ascending lexicographical order , which is not the same as numerical order. Returns the sorted array.
Plus this special case:
- Array.length - simply calling Array.length will not change the array. Instead it will return the numerical length of the array. However, if you assign a value to the array length that is smaller than the current array length then you will remove items from the end of the array. Here’s an example:
const ingredients = ['garlic', 'onions', 'salt'];
ingredients.length = 1;
console.log(ingredients); // ["garlic"]
So remember, CF SUS PPRS (and sometimes length) !
Related posts:
Helpful references:
Have feedback on this topic?