Middle
Do you know about mutable and immutable array methods? For example, what is the difference between splice and filter?
sobes.tech AI
Answer from AI
Mutable array methods modify the original array, while immutable ones return a new array without changing the original.
For example:
splice— a mutable method. It modifies the original array by removing or adding elements.
const arr = [1, 2, 3, 4];
arr.splice(1, 2); // removes 2 elements starting from index 1
console.log(arr); // [1, 4]
filter— an immutable method. It returns a new array with elements that pass the test, without changing the original.
const arr = [1, 2, 3, 4];
const filtered = arr.filter(x => x > 2);
console.log(filtered); // [3, 4]
console.log(arr); // [1, 2, 3, 4]
The choice between them depends on the task: if you need to preserve the original data, it is better to use immutable methods.