Explain the purpose of the following JavaScript array methods: (a) concat() (b) reverse()
Show Hint
Be careful with reverse()! Because it mutates the original array in-place, if you want to keep the original array unchanged, make a copy first using the spread operator or slice(): const reversed = [...original].reverse();.
Step 1: Analyzing the concat() Array Method:
The concat() method is used to merge two or more arrays, or append values to an existing array, without modifying any of the original arrays.
• Immutability (Non-mutating): It is a non-mutating method. Instead of changing the original arrays, it returns a brand-new array containing the combined elements of the source arrays.
• Usage Example:
var array1 = [1, 2];
var array2 = [3, 4];
var newArray = array1.concat(array2); // returns [1, 2, 3, 4]
Step 2: Analyzing the reverse() Array Method:
The reverse() method reverses the order of elements in an array in-place.
• Mutability (In-place Mutation): It is a mutating method. It modifies the original array directly. The first array element becomes the last, and the last array element becomes the first.
• Usage Example:
var myArray = ['a', 'b', 'c'];
myArray.reverse();
// myArray is now mutated directly to ['c', 'b', 'a']
Step 3: Comparative Summary: