JavaScript array methods Push, Pop, Shift and Unshift
In this article we explain you Push(), Pop(), Shift() and Unshift() method one by one with example in JavaScript. These methods use for add or remove items from the beginning or end of arrays.
- How to convert comma separated String into an Array in JavaScript
- How to convert an Array to a String in JavaScript
- JavaScript Spread Operator
- ES6 Rest Parameter in JavaScript
- How to use Map, Filter, and Reduce in JavaScript
shift()
and unshift()
method remove an element and append elements to the beginning of an array respectively.
Array Methods in JavaScript
1. push()
The push()
method can add one or more elements to the end of an array and returns a new array length.
var colours=["Black", "Blue"];
colours.push("Yellow");
// Output: ["Black", "Blue","Yellow"]
2. pop()
The pop()
method can remove an element from the end of an array and return array.
var colours=["Black", "Yellow","Orange"];
colours.pop();
// Output: ["Black", "Yellow"]
3. shift()
The shift()
Method removes the first element of an array. This method like the pop() method, but it works at the beginning of the array.
var colours=["Black", "Yellow","Orange"];
colours.shift();
// Output: ["Yellow","Orange"]
4. unshift()
The unshift()
method can add one or more elements to the beginning of an array and returns a new array length.
var colours=["Black"];
colours.unshift("Blue");
// Output: ["Blue","Black"]
colours.unshift("Yellow","Orange");
// Output: ["Yellow","Orange","Blue","Black"]
That’s it for today.
Thank you for reading. Happy Coding..!!