CodingBison

Arrays are objects and so they are are mutable. We can easily add new elements, modify and delete existing elements. This page talks about several methods that add, modify, and delete array elements: push(), pop(), unshift(), shift(), concat(), and splice(). These methods are provided by Array.prototype and all arrays inherit them automatically.

Let us begin with their signatures:

 var newArrayLen = varArray.push(varElem1, varElem2, ..);
 var elem        = varArray.pop();
 var newArrayLen = varArray.unshift(varElem1, varElem2, ..);
 var elem        = varArray.shift();
 var newVarArray = varArray.concat(varElem1, varElem2, ..);
 var newVarArray = varArray.splice(startIndex, endIndex, varElem1, varElem2, ..);

Methods push() and pop() methods add and delete elements at the end of the array, respectively. The push() methods adds one or more elements at the end of the array; when done, push() returns the new array length. On the contrary, the pop() method deletes the last element (and only last element) of the array and it returns the deleted element.

We can use push() and pop() methods to mimic a stack behavior where instructions can be added at the tail of the queue and once they are done executing, they can be deleted from the tail.

Methods unshift()/shift() are yet another way to add/delete elements. However, unlike push()/pop(), these methods add or delete elements at the beginning of the array.

The unshift() method shifts all elements towards the right to create space for one or more element or more and then adds the new element or elements at the start of the array; when done adding, the unshift() method returns the new length of the array.

The shift() method does the opposite, it shifts all the elements towards left by one space and in this process, automatically removes the first element. This method returns the deleted element.

The next method in the list is concat() and we can use it to concatenate an array with additional elements; these additional elements can even be arrays! Method concat() differs from push()/unshift() methods in the sense that it returns a new array that contains elements from the original array as well as the additional elements. Also, it does not modify the original array.

The last method splice() is a fairly unique method because we can use the same method to both add and delete elements. Method splice() accepts several arguments. The first argument is the array index which specifies the position at which deletion/addition should be done. The second argument specifies the number of elements that needs to be deleted starting at the index. The third element and beyond specify the elements that need to be added starting at the index (specified by the first argument).

Having described these methods, let us go through three examples that show their usage. The first example shows examples of push() and pop() methods.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define an array. 
 var a = [80, 101];

 var x = a.pop();                 // Returns 101
 elem.innerHTML += a;             // a equals [80]
 elem.innerHTML += a.length;      // a.length is 1 

 x = a.push("Dragon");            // Returns 2
 elem.innerHTML += a;             // a equals [80, "Dragon"];
 elem.innerHTML += a.length;      // a.length is 2 

 x = a.push(237, 280);            // Returns 4
 elem.innerHTML += a;             // a equals [80, "Dragon", 237, 280];

 x = a.push(["Emrys", "Merlin"]); // Returns 5
 elem.innerHTML += a;  // a equals [80, "Dragon", 237, 280, ["Emrys", "Merlin"]]; 
 </script>
 </html>

The above output shows that both push()/pop() methods automatically update array's length. Note that with push() we can insert multiple elements in one go. However, if we pass an array as an argument, then push() method inserts the passed array as it is, instead of inserting its element one by one.

Note that method pop()/shift() with the using delete operator to delete an element. When we use the delete operator, then the array length remains unchanged, but with both pop()/shift(), the array length automatically decreases by one. Also, with delete, the element value present at the deleted index is still "undefined", but with pop()/shift(), the element itself is deleted. However, the plus point when using delete is that we are not constrained to delete the element at either the beginning or the end of the array -- delete can "remove" an element irrespective of its location.

The second example (provided below) shows analogous examples of unshift() and shift() methods. The behavior is similar to that of the push()/pop() example, except that elements are added/deleted at the start of the array instead of its end.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define an array.
 var a = [80, 101];

 var x = a.shift();                  // Returns 80 
 elem.innerHTML += a;                // a equals [101]
 elem.innerHTML += a.length;         // a.length is 1

 x = a.unshift("Dragon");            // Returns 2
 elem.innerHTML += a;                // a equals ["Dragon", 101]
 elem.innerHTML += a.length;         // a.length is 1

 x = a.unshift(237, 280);            // Returns 4
 elem.innerHTML += a;                // a equals [237, 280, Dragon, 101]

 x = a.unshift(["Emrys", "Merlin"]); // Returns 5
 elem.innerHTML += a;    // a equals [["Emrys", "Merlin"], 237, 280, Dragon, 101]
 </script>
 </html>

The third and the last example show usage of the remaining two methods: concat() and splice().

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define an array.
 var a = [80, 101];

 var b = a.concat("Dragon");
 elem.innerHTML += a;  // a equals [80, 101]
 elem.innerHTML += b;  // b equals [80, 101, "Dragon"] 

 b = a.concat([237, ["Emrys", "Merlin"]]);
 elem.innerHTML += a;  // a equals [80, 101]
 elem.innerHTML += b;  // b equals [80, 101, 237, ["Emrys", "Merlin"] 

 a = [80, 101, 237, "Emrys", "Merlin"];
 b = a.splice(1,3);
 elem.innerHTML += a;  // a equals [80, "Merlin"]
 elem.innerHTML += b;  // b equals [101, 237, "Emrys"]

 b = a.splice(0,1, "Gandalf", "Trolls");
 elem.innerHTML += a;  // a equals ["Gandalf", "Trolls", "Merlin"]
 elem.innerHTML += b;  // b equals [80]
 </script>
 </html>

The above example demonstrates that with concat(), the original array remains intact. With concat(), we can input arrays as well and it splits the passed array into elements; however, if the passed array itself contains an array, then concat() does not split that and adds that array as it is; thus, concat() performs only one level of splitting array elements. Method splice() differs from concat() because it removes a sub-array from the original array and returns that as a new array; the remaining elements stay with the old array.





comments powered by Disqus