Arrays is used for lists or collections of items. This can be strings, numbers or objects, anything really.
It's hard to work with a large number of variables to store lots of items. When dealing with problems like these we use arrays which is good for making lists or collections.
​
You can use an array literal or the new keyword to create a JavaScript array.
​
These examples shows you how the syntax is:
The two ways in the syntax example above does exactly the same, so it's up to you to decide which one you like the best. But there is no need to use the New Array() method as the array literal is quicker, just as readable and very common way of creating arrays.
​
We can store anything inside a JavaScript array and it's easy to set up. Just look at this example:
One important thing to remember when dealing with arrays is that the first item is placed at position 0 and the second item is placed at position 1 and so on. If you don't remember you can be in trouble when accessing the array or iteration over it.
In the example above we created an array and added items to it at the same time. It is possible to create an empty array and fill it later.
​
Example:
Here you see that the array starts out empty and we start filling it from position 0.
​
When accessing the array it's important to remember the positioning of the element you want to access. We can access the elements in the array by referring to the index number they have in the array.
​
Let's have a look at how to get one of the items inside the array.
We have now looked at what arrays are and how to create them. Arrays stores items as in a list and is a great way of creating collections for things we need in our script. In the next pages we will look into how to iterate the lists and how to sort them.