← Home

Javascript Arrays

EXAMPLES!

Now that we've covered the basic structure of a JavaScript Array, let's take a look at 3 different ways an array can be utilized.

1. Specifying an element within an Array
				
var cities = [ "NYC" , "Chicago" , "Miami"] ;
				
			

We can access an array element by referring to its index number.

Each item (city) is assigned an index number within the array. The first item will be [0], then [1], [2], and so on.

So...

				
var NYC = cities[0]
var Chicago = cities[1]
var Miami = cities[2]
				
			

...and so on!

Now, let's say I want to specify/access "MIAMI".

With "Miami" having an index number of [2], all there is left to do is add this to our function!

				
var cities = ["NYC", "Chicago", "Miami" ];
function = cities[2]; 
				
			
2. The Length Property

The length property of an array will specify the number of all array elements. In our example, we have a total of 3 array elements.

JavaScript code for Array Length Property:

				
var cities = ["NYC", "Chicago", "Miami" ];

console.log(cities.length);
// 3 

				
			
3. The Difference between Arrays and Objects

Remember! Although an array is a special type of object, in JavaScript code, they are written in different ways...

				
arrays use NUMBERED indexes.

objects use NAMED indexes.