Push, Pop, Shift, and Unshift Array methods in JavaScript
Table of Contents
In this post, we'll learn about the JavaScript Array methods push
, pop
, shift
, and unshift
.
These methods are used when you want to add or remove elements from the start or the end of an array.
Push
Use the push
method to add an element to the end of an array.
JAVASCRIPTlet fruits = ["apple", "banana", "orange"];
fruits.push("grape");
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']
push
returns the new length of the array.
Pop
Use the pop
method to remove an element from the end of an array.
JAVASCRIPTlet fruits = ["apple", "banana", "orange"];
fruits.pop();
console.log(fruits); // ['apple', 'banana']
pop
returns the element that was removed.
Shift
Use the shift
method to remove an element from the start of an array.
JAVASCRIPTlet fruits = ["apple", "banana", "orange"];
fruits.shift();
console.log(fruits); // ['banana', 'orange']
shift
returns the element that was removed.
Unshift
Use the unshift
method to add an element to the start of an array.
JAVASCRIPTlet fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ['apple', 'banana', 'orange']
unshift
returns the new length of the array.
Conclusion
We've taken a look at the four most common array methods for manipulating the start and end of arrays, push
, pop
, shift
, and unshift
.
Hopefully you learned something useful and enjoyed reading this post!
- Getting Started with Svelte
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor