JavaScript Array Operations

This article explains the basic functions operated on array to implement various insert and delete operations.

Javascript Array: Push() Method

The push() method can append one or more elements to the end of an array. This alters the array on which the method was called.


var data = [ "X" ];
data.push( "A" );
data.push( "B", "C" );
console.log( data );

console output:

["X", "A", "B", "C"]

The push() method can take multiple arguments, each of which will be appended to the array in the order it was passed-in (left-to-right); if you pass push() an array value, however, the array simply gets appended as a single element (a nested array). If you want to append an array to another array, take a look at the concat() method.

Javascript Array: Pop() Method

The pop() method pulls the last element off of the given array and returns it. This alters the array on which the method was called.


// Build an array of test data.
var data = [ "A", "B", "C" ];
// Pop the element off of the end of the array.
console.log( data.pop() );
console.log( data );

console output:

C
["A", "B"]

If you call pop() on an empty array, it returns an undefined value.

Javascript Array: Unshift() Method

The unshift() method is like the push() method, only it works at the beginning of the array. The unshift() method can prepend one or more elements to the beginning of an array. This alters the array on which the method was called.


var data = [ "X" ];
data.unshift( "A" );
data.unshift( "B", "C" );
console.log( data );

console output:

["B", "C", "A", "X"]

Notice that when we pass the unshift() method multiple arguments, it prepends them in a right-to-left order such that the resultant array mimics the appearence of the unshift() arguments.

Javascript Array: Shift() Method

The shift() method is like the pop() method, only it works at the beginning of the array. The shift() method pulls the first element off of the given array and returns it. This alters the array on which the method was called.


// Build an array of test data.
var data = [ "A", "B", "C" ];// Shift the element off of the beginning of the array.
console.log( data.shift() );
console.log( data );

console output:

A
["B", "C"]

If you call shift() on an empty array, it returns an undefined value.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s