Introduction
When you're working with JavaScript, arrays are going to be the most important object you work with due to how common they are, and their endless applications when it comes to software development, or writing algorithms. Having an understanding of array methods is a very important skill to posses as a developer.
Not only is it important for developers to have an understanding of array methods, but also the different types. In JavaScript, there are two types of array methods: copying methods and mutation methods. To explain the difference between the two, I'll include a short demonstration below.
Let's look at a small example, say we have an object that is a basic array of integers:
let numbers = [1, 2, 3, 4]A simple array of numbers.
Now, we are going to call two methods on this array, one will be a mutating method, and the other will be a copying method.
Mutation Method
numbers.push(5)
console.log(numbers) // Output: [1, 2, 3, 4, 5]Adding 5 to our array using .push()
Copying Method
numbers.concat(5)
console.log(numbers) // Outputs: [1, 2, 3, 4]Adding 5 to our array using .concat()
Did you see that? Notice how in both examples the array of numbers logged to the console is different. In the mutation method example, when we added 5 to the array, the numbers array reflected that change when we logged it. In the copying method example, the numbers array looks no different, even after we added 5 to the array. I know what you're thinking, no, .concat() is not broken, it's behaving perfectly normally. I'll even prove it to you. Let's try this again, but let's assign numbers.concat() to a variable this time.
let newArray = numbers.concat(5)
console.log(numbers) // Output: [1, 2, 3, 4]
console.log(newArray) // Output: [1, 2, 3, 4, 5]Adding a new number to our array using .concat(), but assigning it to a variable.
When we logged numbers, we see no difference, when we log newArray, we see the 5 that we added with .concat(). This is where the difference between mutation methods and copying methods lie.
