JavaScript Add to List : examples
An array is a single variable in JavaScript which holds multiple elements inside it. Each element inside the array has a unique index assigned to it. You can access the element inside the array using that index. Array can be changed or mutated with many built in methods. Let’s cover some methods to add new elements to an array.
Create a new Array:
const myFirstArray = [];
Array.Push():
The push method will add the new element at the end. It will mutate the original array, which means it will update the original array. The push method can take N number of elements together & adds them to the array.
myFirstArray.push(1);
console.log(myFirstArray);
// [1]
myFirstArray.push(2,3,4);
Array.Splice():
The splice method is generally used to remove the element from an array, but you can use it to append the element. It will mutate the original array. The splice method takes 3 arguments:
- startIndex: Index of an array where you want to add/remove an element.
- deleteCount: number of elements to be removed(0 if you are adding element).
- items: elements to be added(null if you are removing from an array).
myFirstArray.splice(myFirstArray.length, 0, 5);
console.log(myFirstArray);
// [1,2,3,4,5]
Array.Length:
Length gives a count of all the elements inside the array. You can directly assign elements to a specific index. It will mutate the original array.
myFirstArray[myFirstArray.length] = 6;
Array.Concat:
Concat method merges the second array with an existing array. You can store the result either in a new array or an existing array.
myFirstArray = myFirstArray.concat([7,8]);
Array.Spread:
The spread syntax is used to expand each array element into individual elements. A very popular application is to use spread to create a copy or merge two separate arrays.
const myFirstArray = [1, 2];
const mySecondArray = [3, 4];
const newArray = [...myFirstArray, ...mySecondArray];
newArray; // [1, 2, 3, 4]