Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Array:

var person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, person.firstName returns John:

Object:

var person = {firstName:"John", lastName:"Doe", age:46};
 

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
 

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Examples

var x = cars.length;   // The length property returns the number of elements
var y = cars.sort();   // The sort() method sorts arrays

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array elements).

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;   // the length of fruits is 4
The length property is always one more than the highest array index.



Practice Excercise Practice now