Array in JavaScript with push(), pop(), splice()

Freddychris A
3 min readOct 31, 2020

ARRAY:

We only worked with few pieces of data at a time. A couple of numbers, some strings, and maybe a few Booleans.

What happens when you want to work with lot of data all at once?

We can do just that with a data structure called an array.

Arrays are a data structure that can hold multiple data values, kind of like list.

An array is useful because it stores multiple values into a single, organized data structure. You can define a new array by listing values separated with commas between square brackets ‘[ ]’.

ARRAY DECLARATION

Array declaration

But strings aren’t the only type of data you can store in an array. You can also store numbers, booleans… and really anything!

You can even store an array in an array to create a nested array!

nested array

Indexing

Remember that elements in an array are indexed starting at the position 0. To access an element in an array, use the name of the array immediately followed by square brackets containing the index of the value you want to access.

How array index works
Program to array index

Array.length

You can find the length of an array by using its LENGTH property.

Find Length of array

So you can find length of an array, but what if you want to modify an array?

Arrays have quite a few built-in methods for adding and removing elements from an array. The two most common methods for modifying an array are “PUSH( )” and “POP( )”.

Push

You can use the PUSH( ) method to add elements to the end of an array.

Push

Ferrari will insert in the last array index of the carfamily.

Pop

Alternatively, you can use the POP( ) method to remove elements from the end of an array.

pop

With the POP( ) method you don’t need to pass a value; instead,POP( ) will always remove the last element from the end of the array. Also, POP( ) returns the element that has been removed in case you need to use it.

Splice

Splice( )is another handy method that allows you to add and remove elements from anywhere within an array.

While PUSH( ) and POP( ) limit you to adding and removing elements from the end of an array, Splice( ) lets you specify the index location to add new elements, as well as the number of elements you’d like to delete (if any).

splice

· Arg1= Mandatory argument. Specifies the starting index position to add/remove items. You can use a negative value to specify the position from the end of the array e.g., -1 specifies the last element.

· Arg2= Optional argument. Specifies the count of elements to be removed. If set to 0, no items will be removed.

· ITEMS….ITEMS are the items to be added at index position arg1 .Splice( ) method returns the item(s) that were removed.

--

--