Push, Pop, Shift and Unshift methods in Javascript

Javascript Pop(), Push() Shift(), and Unshift() method is used to perform the action on the array such as adding the elements to the existing array or removing the elements from an array.

For this tutorial, I am using chrome developer's tool to test the code. You can use other tools if you want to.

For example, you can run the code to test in the terminal using nodejs. The following are the steps to test the code in node js.

  1. Create a file index.js
  2. Open the terminal and navigate to the directory where you have created index.js
  3. Run node <space> index.js

Javascript Pop() Method:

The pop() method is used to remove the last element from an array. When the pop() action is performed on an array the new size of the element is returned.

For example:

var house = ['fan', 'geyser', 'door', 'fridge', 'washing-machine', 'car'];
house.pop();

console.log(house);

In the above code, pop() method is performed on house array. The Pop() method will remove the last element of the array which is a car in the above code and return the new length of the array. Below the output of the above code.

["fan", "geyser", "door", "fridge", "washing-machine"]
	0: "fan"
	1: "geyser"
	2: "door"
	3: "fridge"
	4: "washing-machine"

Note: If you perform pop() on the empty array it will return undefined

Javascript Push() Method:

The push() method is used to add an element on the array. You can add multiple elements in an array using the push method. When you perform push method on array it will append the element at the end and return the new length of an array.

For example:

var house = ['fan', 'geyser', 'door', 'fridge', 'washing-machine'];
house.push('ac', 'sofa');

console.log(house);

The output of the above code will be

0: "fan"
1: "geyser"
2: "door"
3: "fridge"
4: "washing-machine"
5: "ac"
6: "sofa"
length: 7

Javascript Shift() Method:

The shift() method is used to remove the first element from the array and return the new length of the array.

shift() method will return undefined if we perform on an empty array.

For example:

var house = ['fan', 'geyser', 'door', 'fridge', 'washing-machine'];
house.shift();

console.log(house);

shift() method will remove the first element fan from the house array. Below is the output of the above code

0: "geyser"
1: "door"
2: "fridge"
3: "washing-machine"
length: 4

Javascript Unshift() Method:

The unshift() method is used to insert the element at the beginning of the array. You can also pass multiple elements to insert in the array. It will append the elements in the same order you passed in the unshift method and return the new length of the array.

For example:

var house = ['fan', 'geyser', 'door', 'fridge', 'washing-machine'];
house.unshift('light', 'watch');

console.log(house);

The above code will output the following

0: "light"
1: "watch"
2: "fan"
3: "geyser"
4: "door"
5: "fridge"
6: "washing-machine"
length: 7