JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)
What are the array mutation methods?
JavaScript array methods can be categorized into two groups:
- Mutating methods: These are the methods that directly modify the original array.
- Non-mutating methods: These methods return a new array without altering the original one.
There are 9 methods in total that mutate the arrays,
- push: Adds one or more elements to the end of the array and returns the new length.
- pop: Removes the last element from the array and returns that element.
- unshift: Adds one or more elements to the beginning of the array and returns the new length..
- shift: Removes the first element from the array and returns that element.
- splice: Adds or removes elements from the array at a specific index position.
- sort: Sorts the elements of the array in-place based on a given sorting criteria.
- reverse: Reverses the order of elements in the given array.
- fill: Fills all elements of the array with a specific value.
- copyWithIn: Copies a sequence of elements within the array to a specified target index in the same array.
Practical Code Example
javascript
// Array Mutation Methods (modify array in place):
// push(), pop(), shift(), unshift(), splice(), sort(), reverse()
// Modern Non-Mutating Alternatives (ES2023):
const original = [3, 1, 2];
const sorted = original.toSorted(); // [1, 2, 3] (original stays [3, 1, 2])
const reversed = original.toReversed(); // [2, 1, 3]
const spliced = original.toSpliced(0, 1, 99); // [99, 1, 2]