JavaScript Array Push and Pop

JavaScript Arrays can be manipulated through various methods like Push and Pop provided by the Array class. Sometime back I had written on Slice() and Splice() in JavaScript. In this post, let us see an example of how to use the Push and Pop methods to manipulate arrays

Push() – Adds one or more elements to the end of an array and returns the new length of the array

<script type="text/javascript">
var
nums = new Array("One", "Two", "Three", "Four");
document.write("Original Array: " + nums + "<br />");
document.write(nums.push("Five", "Six") + "<br />");
document.write("Modified Array: " + nums + "<br />");
</script>

javascript push

To add more elements to the array at once, give the argument in the form of an array

<script type="text/javascript">
var
nums = new Array("One", "Two", "Three", "Four");
document.write("Original Array: " + nums + "<br />");
document.write(nums.push(["Five", "Six"]) + "<br />");
document.write("Modified Array: " + nums + "<br />");
</script>

javascript push array

Compare the code above with the previous code. Observe that when the new item added is itself an array, then each value is not added individually, but as one single item. Hence the new length of the array in this example is 5 and not 6.

Note: Unlike the concat() method, push() modifies the array ‘directly’ rather than creating a new array.

Pop() - Removes the last element of an array and returns it. The Pop() method changes the original array

<script type="text/javascript">
var
nums = new Array("One", "Two", "Three", "Four");
document.write("Original Array: " + nums + "<br />");
document.write("Element Removed: " + nums.pop() + "<br />");
document.write("Modified Array: " + nums + "<br />");
</script>

javascript pop

Check plenty of other JavaScript tips over here

No comments:

Post a Comment