Tell me about array methods: which ones do you use, do they mutate the array, and what do they return?
sobes.tech AI
Answer from AI
JavaScript has many methods for working with arrays. Here are the main ones that I often use:
-
map(callback)— creates a new array by applying a function to each element. Does not mutate the original array. -
filter(callback)— creates a new array with elements that pass the check. Does not mutate. -
reduce(callback, initialValue)— reduces the array to a single value by applying an accumulator function. Does not mutate. -
forEach(callback)— executes a function for each element, returnsundefined. Does not mutate, but you can change elements inside the function. -
push(element)— adds an element to the end of the array. Mutates the array, returns the new length. -
pop()— removes the last element. Mutates, returns the removed element. -
shift()— removes the first element. Mutates, returns the removed element. -
unshift(element)— adds an element to the beginning. Mutates, returns the new length. -
slice(start, end)— returns a new array with a copy of part of the original. Does not mutate. -
splice(start, deleteCount, ...items)— modifies the array by deleting and/or adding elements. Mutates, returns the deleted elements. -
sort()— sorts the array in place. Mutates, returns the sorted array. -
concat(array)— returns a new array by combining the original with another. Does not mutate.
Example of using map and filter:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
It is important to remember that methods that mutate the array change the original, which can lead to bugs if the state is not controlled. Methods that return a new array help write cleaner and more predictable code.