JavaScript Array Object with Example

Updated on     Kisan Patel

An array is an ordered collection of elements. JavaScript arrays are used to store multiple values in a single variable.

In JavaScript, an array can be created using formal object notation, or it can be initialized using literal notation, as shown in the following code.

var arrayObj = new Array("val1", "val2"); // array as object
var arrayLit = ["val1", "val2"]; // array as literal

A new Array object is created using the new operator, as follows.

var arrObject = new Array();

You can also create a new array that has some values.

var arrObject = new Array("Toyota","BMW");

You can create an array literal by using square brackets to hold the array values.

var arrLiteral = ["Toyota","BMW","Honda"];

An array, whether literal or object, can hold values of different data types.

var arrObject = new Array("BMW", 34, true); // string, number, boolean
var arrLiteral = [arrObject, "Honda", 18, false); // object, string, number, boolean

Array elements can be accessed directly, using square brackets containing their index (position in the array).

In addition, array elements can be set using the same index, which automatically creates the array element if it doesn’t exist.

var arrObject = new Array();
arrObject[0] = "Toyota"; // array now has one element
alert(arrObject[0]); // prints Toyota

Arrays in JavaScript are zero-based, which means the first element index is zero, and the last element is at the array length, minus 1.

var Cars = new Array("Toyota","BMW","Honda","Suzuki");
alert(Cars[0]); // print Toyota
alert(Cars[3]); // print Suzuki

Array Object Methods

Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its position
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array

 


JavaScript

Leave a Reply