54. Adding Elements to Arrays
JavaScript provides several built-in methods to add elements to an array.
1. .push(): Adding to the End
The push() method adds one or more elements to the end of an array. It returns the new length of the array.
javascript const cart = ['milk', 'bread'];
cart.push('eggs'); // Add one element cart.push('cheese', 'butter'); // Add multiple elements
console.log(cart); // ['milk', 'bread', 'eggs', 'cheese', 'butter']
2. .unshift(): Adding to the Beginning
The unshift() method adds one or more elements to the start of an array. This operation is generally slower than push() because all existing elements must be re-indexed.
javascript const queue = ['person B', 'person C'];
queue.unshift('person A');
console.log(queue); // ['person A', 'person B', 'person C']
Adding by Index
You can also add elements by explicitly assigning an index beyond the current length. This creates 'empty slots' in the array if the gap is large.
javascript let sparse = [10, 20]; sparse[5] = 60; console.log(sparse); // [10, 20, <3 empty items>, 60]