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:
Objects use names to access its "members". In this example, person.firstName
returns John:
Object:
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[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 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
fruits.length; // the length of fruits is 4
length
property is always one more than the highest array index. Practice Excercise Practice now