Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Array Deep Dive: Adding and Deleting Elements Array.push(), Array.unshift(), and delete

Monday, November 29, 2021

JavaScript Array Deep Dive: Adding and Deleting Elements Array.push(), Array.unshift(), and delete

When you define an object as an Array in JavaScript you get the benefits of inheriting some useful methods with it.  Some of the common methods are those that allows you to add and delete elements from an array.  The .push() method adds an element at the end of the array, the unshift() method adds an element at the beginning of the array.  The delete keyword deletes an element at the specified index.

Let say you have an the following array:

var numbers = [3,4];

If you output the array in the browser console you will see that the array has two elements with the number 3 occupying index 0 and the number 4 occupying index 1.


















Now let's use the push method to add a number 5 to the end of the array with the following code

numbers.push(5);

If output the array in the console you will see that there are 3 elements now with 5 being the last element in the array.












The next thing we want to do is add an element in the beginning of the array with the unshift() method.  Let's add a number 2 as the first element of the array with the following code numbers.unshift(2);

If you output the array in the browser console you will see that now we have four elements not with the values 2,3,4,5












To get rid of the first element in the array you simply call the shift() method like the following code to get right the number 2 in the numbers array:

numbers.shift();











The opposite of shift() is the pop() method, the pop() method will remove the last element in the array.

numbers.pop(); will leave you with two elements in the array 3,4










The last thing we are going to look at is the delete keyword.  With delete keyword we can delete an element based on the index of the array.  For example we can delete the 3 in the array by specifying the index of the element, like the following code

delete numbers[0];

If you output the array in the browser console now you get have only one element remaining which is the element with the value 4.

There's something interesting when using the delete keyword.  Even though we deleted the number 3 successfully.  The length of the array is still 2, meaning there's an empty element occupying the first element of the array.  So when you using the delete keyword there's some residual side effects that you would normally think about.  It's almost like a soft delete.






1 comment:

  1. Not bad this is surely nice way to add and remove in simple and easy method.

    ReplyDelete

Search This Blog