let myArray = [1, 2, 3];
In this example,
myArray is an array that contains three elements: 1, 2, and 3.
let myArray = [1, 2, 3]; console.log(myArray); // Output: 1 myArray = 5; console.log(myArray); // Output: [1, 5, 3]
In the first
myArray accesses the first element of the array, which is 1. In the second statement,
myArray modifies the second element to the value 5. The resulting array is [1, 5, 3].
Merging Two Arrays
- The Spread operator: The spread operator (
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let mergedArray = [...array1, ...array2]; console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
2. Concatenation using the
concat() method: The
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; const mergeResult = array1.concat(array2); console.log(array1); // Output: [1, 2, 3, 4, 5, 6]
push() method: The
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; Array.prototype.push.apply(array1, array2); console.log(array1); // Output: [1, 2, 3, 4, 5, 6]
These methods create a new array that contains elements from both arrays. Note that the original arrays remain unchanged, and the merged array is assigned to a new variable (
mergedArray in the examples above). You can also choose to modify one of the existing arrays if desired and you can always choose a method that best fits your coding style.