Mutator methods in JavaScript are array methods that modify the original array. Here are some commonly used mutator methods and how you can use them:
-
push()
- Adds one or more elements to the end of an array.
const arr = [1, 2, 3]; arr.push(4); // Adds 4 to the end of the array console.log(arr); // Output: [1, 2, 3, 4]
-
pop()
- Removes the last element from an array.
const arr = [1, 2, 3]; const popped = arr.pop(); // Removes 3 from the end console.log(arr); // Output: [1, 2] console.log(popped); // Output: 3
-
shift()
- Removes the first element from an array.
const arr = [1, 2, 3]; const shifted = arr.shift(); // Removes 1 from the beginning console.log(arr); // Output: [2, 3] console.log(shifted); // Output: 1
-
unshift()
- Adds one or more elements to the beginning of an array.
const arr = [2, 3]; arr.unshift(1); // Adds 1 to the beginning of the array console.log(arr); // Output: [1, 2, 3]
-
splice()
- Changes the contents of an array by removing or replacing elements.
const arr = [1, 2, 3, 4, 5]; arr.splice(2, 1); // Removes 1 element starting from index 2 console.log(arr); // Output: [1, 2, 4, 5] arr.splice(1, 2, 'a', 'b'); // Removes 2 elements starting from index 1 and adds 'a' and 'b' console.log(arr); // Output: [1, 'a', 'b', 5]
-
reverse()
- Reverses the elements in an array.
const arr = [1, 2, 3]; arr.reverse(); // Reverses the array console.log(arr); // Output: [3, 2, 1]
-
sort()
- Sorts the elements of an array in place and returns the sorted array.
const arr = [3, 1, 2]; arr.sort(); // Sorts the array in ascending order console.log(arr); // Output: [1, 2, 3] // For custom sorting logic const arr2 = [10, 2, 5, 1]; arr2.sort((a, b) => a - b); // Sorts in ascending order based on custom logic console.log(arr2); // Output: [1, 2, 5, 10]
Remember that mutator methods alter the original array. If you want to avoid modifying the original array, consider using non-mutator methods or creating a copy of the array before applying mutator methods.