Rest and spread with arrays

Interestingly enough, the rest and spread syntax can also be used with arrays. Consider the following code:

let firstArray = [1, 2, 3, 4, 5]; 
console.log(`firstArray=${firstArray}`); 
 
firstArray = [...firstArray, 6, 7, 8]; 
console.log(`firstArray=${firstArray}`); 

Here, we have defined an array name firstArray that has five elements, which are the numbers 1 through 5. We are then logging this array to the console. Note the next line of this code snippet, where we are using the rest syntax to append the values 6, 7, and 8 to the existing array. We are then logging the firstArray array to the console. The output of this code is as follows:

firstArray=1,2,3,4,5
firstArray=1,2,3,4,5,6,7,8

As we can see, the values 6, 7, and 8 have been appended to the original array, all through using the rest and spread syntax in a slightly novel form. Note that this syntax can be used with arrays of any type, and can also be used as a substitute for array elements. Consider the following code:

let secondArray = [ 
    { id: 1, name: "name1" }, 
    { id: 2, name: "name2" } 
] 
console.log(`secondArray : ${JSON.stringify(secondArray)}`); 
 
secondArray = [ 
    { id: -1, name: "name-1" }, 
    ...secondArray, 
    { id: 3, name: "name3" }, 
]; 
console.log(`secondArray : ${JSON.stringify(secondArray)}`); 

Here, we start with an array named secondArray that contains an array of complex types, where each type has an id and a name property, which we then log to the console.

Note, however, the third line of this code snippet. We are using the rest and spread syntax to redefine the elements that are in the array. This array now contains an element with an id property of -1, then all elements of the original array (using the rest ... syntax), and then an element with an id property of 3. The output of this code snippet is as follows:

secondArray : [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
secondArray : [{"id":-1,"name":"name-1"},{"id":1,"name":"name1"},{"id":2,"name":"name2"},{"id":3,"name":"name3"}]

As can be seen from the output, the secondArray array started out with only two elements, and then, by using the rest and spread syntax, we have inserted an element at the beginning of the array, and an element at the end of the array.