6.2 Adding Elements to an Array
Let's start by declaring a constant called Numbers and we define it on an array with two elements, 3 and 4. Now notice that here I have declared Numbers as constant, this means that we cannot reassign numbers to anything else If we do, we get this error, error assignment to a constant variable, but it is perfectly fine to change the contents of this array. We can add new elements or delete existing ones. So constant does not prevent us from changing the contents of an array. Earlier, you learned that arrays are objects, so using dot notation, we can look at all the properties and methods defined in arrays. In this video we will look at 3 of these methods, adding new elements to the end, beginning or middle of an array. The first method we'll use is the push method. So numbers. push, we can pass 1 or more arguments, and those arguments will be placed at the end of this array. So I'm going to pass 5 and 6 now let's do a console. Log of numbers, save the changes, so we have 3 and 4, now we have 5 and 6 at the end. If you want to add elements to the beginning of an array, you use the unshift method. So, numbers. unshift. This basically pushes the elements of this array to the right and adds new elements to the beginning. So, again here, we can pass one or more arguments, I'll pass 1 and 2 Now let's bring this console.log here. So save the changes, we now have 1 and 2 at the beginning of this array. And finally, if you want to add elements to the end of an array, you use the splice method. So we do numbers.splice, with this method we can go to a given position, and add new elements or delete existing elements. Later in this section, we'll look at deleting elements, so for now don't worry about it. Now look at the parameters of this method. The first parameter is start, which is a number. So this is our start position. So let's say in this array, after 1 and 2 here, between 2 and 3, we want to add a new element. So our starting position is here. What is the index of this element? Well, you know arrays have an index of 0. So the index of the first element is 0 and then 1 and here's 2. So our starting position, or starting index, is 2. Now look at the second parameter here, this is the number of deletions which is a number. How many items do we want to delete? None, so I'm going to pass 0, and then look at the third parameter. These are the items that you want to add. So, to set it up, I'm going to add 2 characters here: 'a' and 'b'. Save the changes, 'a' and 'b' are placed after 1 and 2. That's it for this video on adding elements to an array in JavaScript, we'll see you again for finding elements in an array.