Remove the Last Element From an Array in JavaScript

Remove the Last Element From an Array in JavaScript

Array is a variable that holds different types of information in JavaScript. If, you want to remove some elements from the ending or last of the array. In this guide, we will show you how to remove the last element from an array in javascript.

How to Remove the Last Element From an Array in JavaScript

There are a few approaches to remove the last element from an array in javascript:

  • Approach 1: Using the pop() method
  • Approach 2: Using the splice() method
  • Approach 3: Using the slice() method

Approach 1: Using the pop() method

The pop() method helps us to remove or delete the last element from the array and return it. It removes the last element and changes the original array.

Here is an example function of removing the last element from the array javascript using pop:

const lang = ["python", "php", "node"];
lang.pop();
console.log(lang); // ["python", "php"]

Approach 2: Using the splice() method

The splice() method can be used to remove elements from an array by specifying the start index and the number of elements to be removed. To remove the last element, you can use the array’s length as the start index and remove one element.

Here is an example function of removing last element from the array javascript using Splice:

// Example array
let myArray = [1, 2, 3, 4, 5];

// Remove the last element
myArray.splice(myArray.length - 1, 1);

// Display the modified array
console.log("Modified Array:", myArray);

Approach 3: Using the slice() method

The slice() method returns a new array containing the selected elements from an existing array. To remove the last element, you can create a new array by specifying the start index as 0 and the end index as the length of the array minus 1.

Here is an example function of removing last element from the array javascript using slice():

// Sample array
let myArray = [1, 2, 3, 4, 5];

// Creating a new array without the last element using slice()
let newArray = myArray.slice(0, myArray.length - 1);

console.log("New array:", newArray);
console.log("Original array remains unchanged:", myArray);

Conclusion

That’s it; you have learned how to remove the last element from an array in javascript using the pop, splice, and slice method.

Recommended JavaScript Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *