JavaScript provides push() method to add elements to the end of an array. You can even add multiple elements and array to the array using push() method.
Note: push() method modifies the original array and returns the length of the updated array.
let vegetables = ["Potato", "Tomato", "Cabbage"]; vegetables.push("Broccoli"); console.log(vegetables);
Output
["Potato", "Tomato", "Cabbage", "Broccoli"]
You can pass multiple elements to push() method and those elements will be added to the end of the array.
let groceryList = ["Milk", "Bread", "Garlic"]; console.log(groceryList); groceryList.push("Pasta", "Tomato Sauce"); console.log(groceryList);
Output
["Milk", "Bread", "Garlic"] ["Milk", "Bread", "Garlic", "Pasta", "Tomato Sauce"]
You can pass array to push() method and that array will be appended to the array.
let arr = [1, 2, 3, 4]; console.log(arr); arr.push([5, 6, 7]) console.log(arr);
Output
[1, 2, 3, 4] [1, 2, 3, 4, [5, 6, 7]]