remove an element from the end of an array in javascript

There are multiple ways to remove an element from the end of an array in JavaScript. Two commonly used methods are pop() and splice().

  1. Using pop(): The pop() method removes the last element of an array and returns it. The original array gets modified.
index.tsx
let arr = [1, 2, 3, 4, 5];
let last = arr.pop(); // removes 5 from the array and returns it
console.log(arr); // Output: [1, 2, 3, 4]
console.log(last); // Output: 5
166 chars
5 lines
  1. Using splice(): The splice() method can be used to remove an element from a specific index of an array. If we pass negative value to the index parameter of splice(), it starts removing elements from the end. This method also modifies the original array.
index.tsx
let arr = [1, 2, 3, 4, 5];
arr.splice(-1, 1); // removes last element from the array
console.log(arr); // Output: [1, 2, 3, 4]
127 chars
4 lines

Both methods are known to mutate the original array. If you don't want to mutate the original array and want to create a new array without the last element, you can use the slice() method.

index.tsx
let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(0, -1); // creates a new array without the last element
console.log(newArr); // Output: [1, 2, 3, 4]
console.log(arr); // Output: [1, 2, 3, 4, 5]
196 chars
5 lines

gistlibby LogSnag