Ads by ProfitSence
Close

Removing Elements from JavaScript Array Code Example

Last Updated on Wednesday 5th Oct 2022

Example 1: Remove from the end of an array

  • Set the length property to a value less than the current value.
  • Any element whose index is greater than or equal to the new length will be removed.
			
					let arr = [1, 2, 3, 4, 5, 6];
arr.length = 4;
console.log(arr); // [ 1, 2, 3, 4 ]

			
	

Pop Method

  • The pop method modifies the array.
  • It is deleted and the array length reduced.
			
					let arr = [1, 2, 3, 4, 5, 6];
arr.pop();
console.log(arr); // [ 1, 2, 3, 4, 5 ]

			
	

Example 2: Remove from the start of an array

Shift Method

  • The shift method works much like the pop method.
  • Shift removes the first element of a JavaScript array instead of the last.
			
					let arr = [1, 2, 3, 4, 5, 6];
arr.shift();
console.log(arr); // [ 2, 3, 4 , 5, 6]

			
	
  • The shift method returns the element that has been removed
  • Updates the indexes of remaining elements.
  • If there are no elements, or the array length is 0, the method returns undefined.