Different ways to remove an element at the end of the array using JavaScript
Let's see 3 different ways to remove an element at the end of the array
As part of this blog we are going to see how to remove an element at the end of the array in JavaScript using the following methods.
- reduce the length of the array
- using Array.prototype.pop() method
- using Array.prototype.splice() method.
What is an Array
Array is an ordered set of list of values, where each value is specified by an index. And a single array can hold different types of values. eg, a single array can hold both strings and integers.
Lets consider the below set of array, with length 6.
let arrayExample = [1, 2, 3 ,4, 5, 6]
Lets reduce see how we can remove the last element in the array
1) Remove by reducing the length of the array.
By explicitly setting the length of the array to be less, will delete the last value automatically
let arrayExample = [1, 2, 3 ,4, 5, 6];
arrayExample.length = 5; // Changing the length of the array
console.log(arrayExample); //Output : [1,2,3,4,5];
2) Remove using Array.prototype.pop() method.
As per MDN docs, "The pop() method removes the last element from an array and returns that element. This method changes the length of the array".
let arrayExample = [1, 2, 3 ,4, 5, 6];
arrayExample.pop(); // removes the element 6
console.log(arrayExample); //Output : [1,2,3,4,5];
In the above example , the last element in the array is "6". As per pop() method the last element in the array is removed.
3) Remove using Array.prototype.splice() method.
As per MDN docs, " The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place."
let arrayExample = [1, 2, 3 ,4, 5, 6];
arrayExample.splice(arrayExample.length - 1); // returns elements up until 5
console.log(arrayExample); //Output : [1,2,3,4,5];
In the above example, we specify the index value as array length -1 which is 5. Hence it returns the array up until 5 array elements.
References
Check out my other blog posts
- 10 things you can do in chrome developer tools
- 2 Simple ways you can truncate text using CSS
- Create a GitHub Profile README.md with widgets
Lets connect on Twitter | LinkedIn for more web development related tips.