Insert items to the end of an array in JavaScript
This post will discuss how to insert items to the end of an array in JavaScript.
There are several ways to insert an item at the end of an array in JavaScript. Some of the most common functions are:
1. Using push() function
The Array.push() function adds one or more elements to the end of an array and returns the new length of the array. It is simple and effective, and it modifies the original array.
|
1 2 3 4 5 6 7 |
const array = [1, 2, 3]; const newItem = 4; // returns 4 array.push(newItem); console.log(array); // [1, 2, 3, 4] |
2. Using spread syntax
The spread syntax (…) allows us to expand the elements of an iterable (such as an array) into individual arguments. It can be used to create a new array by combining the existing array and the new element. It does not affect the original array, but returns a new array with new items appended.
|
1 2 3 4 5 6 7 8 |
const array = [1, 2, 3]; const newItem = 4; // returns [1, 2, 3, 4] const newArray = [...array, newItem]; console.log(array); // [1, 2, 3] console.log(newArray); // [1, 2, 3, 4] |
3. Using concat() function
The concat() function creates a new array by concatenating two or more arrays. It does not change the original arrays, but returns a new array with new items appended.
|
1 2 3 4 5 6 |
const array = [1, 2, 3]; const newItem = 4; const newArray = array.concat(newItem); console.log(newArray); // returns [1, 2, 3, 4] |
4. Using length property
The length property returns or sets the number of elements in an array. It can be used to insert an item at the end of an array by assigning the item to the index equal to the current length of the array.
|
1 2 3 4 5 6 |
const array = [1, 2, 3]; const newItem = 4; array[array.length] = newItem; console.log(array); // returns [1, 2, 3, 4] |
5. Using splice() function
The Array.splice() function can be used to insert an element at a specific position in an array. It can be used to insert an item at the end of an array by specifying the array length as the start index, 0 as the delete count, and the item as the element to add.
|
1 2 3 4 5 6 |
const array = [1, 2, 3]; const newItem = 4; array.splice(array.length, 0, newItem); console.log(array); // returns [1, 2, 3, 4] |
That’s all about inserting items to the end of an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)