Push & Pop
Lesson 6 of 18 in Coddy's Array Methods in JavaScript course.
The push() method is used to add one or more elements to the end of an array and returns the new length of the modified array.
The pop() method removes the last element from an array and returns the removed element. If the array is empty, pop() returns undefined.
For example :
Imagine you have a shopping list as an array. push() allows you to add new items to the list at the back. It modifies the original array by adding the elements you provide. Think of pop() as taking the last item off your shopping list. It removes the element from the end of the array.
let shoppingList = ["Milk", "Bread", "Eggs"];
let newListLength = shoppingList.push("Cheese", "Apples");
console.log(shoppingList); // Output: ["Milk", "Bread", "Eggs", "Cheese", "Apples"]
console.log(newListLength); // Output: 5 (New length of the array)
let removedItem = shoppingList.pop();
console.log(shoppingList); // Output: ["Milk", "Bread", "Eggs", "Cheese"]
console.log(removedItem); // Output: "Apples" (The removed last item)The above code creates a shopping list array and lets you add items like "Cheese" and "Apples" to the end using push(). It then shows how to remove the last item ("Apples" in this case) from the list using pop().
Challenge
EasyYou have three songs in the queue: "Uptown Funk", "Happy", and "Downtown" as listed in the given playlist array.
Write JavaScript code to delete the last song, add the new song "Dynamite", and log the playlist.
Try it yourself
let playlist = ['Uptown Funk', 'Happy', 'Downtown'];
// Write code here