Javascript Array Methods

Javascript Array Methods: push() and pop()

push() and pop() are the javascript array methods.

The pop() method in JavaScript removes an item from the end of an array, whereas the push() method adds an item to the end of an array.

And when you want to add or remove an item from the beginning of an array, shift() and unshift() methods will be used. Read my other article about shift() and unshift() method. Javascript Array Methods: shift() and unshift()

Javascript Array: push() method.

push() function adds one or more items to the end of an array and returns the new length of the array.

1) Pushing a single item 


var array= ["A", "B", "C", "D"];
var newLength= array.push("E");

console.log(newLength);
//OUTPUT: 5

console.log(array);
//OUTPUT: ["A", "B", "C", "D", "E"]

2) Pushing multiple items

we can also pass multiple items to push() method. which will add multiple items to the end of an array.


var array= ["A", "B", "C"];
var newLength= array.push("D","E");
console.log(newLength);
//OUTPUT: 5

console.log(array);
//OUTPUT: ["A", "B", "C", "D", "E"]

Javascript Array: pop() method.

pop() function removes the last item of an array and returns a new length of an array and returns the removed item.


var array= ["A", "B", "C", "D"];
var element= array.pop();

console.log(element);
//OUTPUT: D

console.log(array);
//OUTPUT: ["A", "B", "C"]

element= array.pop();
console.log(element);
//OUTPUT: C

console.log(array);
//OUTPUT: ["A", "B"]

When the array is empty.

When the array is empty and pop() method is called, it’ll return undefined.


var array= ["A", "B"];
var lastElement= array.pop();
console.log(lastElement);
//OUTPUT: B

console.log(array);
//OUTPUT: ["A"]

lastElement= array.pop();
console.log(lastElement);
//OUTPUT: A

console.log(array);
//OUTPUT: []

lastElement= array.pop();
console.log(lastElement);
//OUTPUT: undefined

console.log(array);
//OUTPUT: []

Here in the above code, you can see that we have called pop() method 3 times and when the last method is called, it returns the value undefined. because there is no item in the array.

I hope you like this article. learn more


Also Read: