JavaScript Tutorial

Javascript Array Methods

There are different array methods supported by Javascript:-

Pushing elements

This push() method allows us to add one or more elements to the end of the array. This method returns the value of the length property that specifies the number of elements in the array.

Input:-

Output:-

Poping elements

This pop() method removes the element at the end of the array and returns the element to the caller. If the array is empty, the pop() method returns undefined.

Input:-

Output:-

Shifting elements

This shift() method removes the first array element and "shifts" all other elements to a lower index. Shifting is equivalent to popping, working on the first element instead of the last.

Input:-

Output:-

Unshifting elements

This unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements. This method returns the new array length.

Input:-

Output:-

Splicing an array

This splice() method allows us to insert new elements into an array while deleting existing elements simultaneously. To do this, we pass at least three arguments with the second one that specifies the number of items to delete and the third one that indicates the elements to insert.

Note that the number of elements to delete needs not to be the same as the number of elements to insert.

Input:-

Output:-

Slicing an array

This method extracts the part of the given array and returns it. This method doesn't change the original array.

The slice() method is represented by the following syntax:

array.slice(start,end)

Here, there are two parameters – start and end.

Start is optional and represents the index from where the method starts to extract the elements.

End is also optional and represents the index at where the method stops extracting elements.

Input:-

Output:-

Merging arrays

This method creates a new array by merging (concatenating) existing arrays.

The concat() method does not change the existing arrays. It always returns a new array and it can take any number of array arguments.

Input:-

Output:-


Go back to Previous Course