Each element in an array is separated by a comma and all of the elements are stored inside square brackets eg. numbers = [1,2,3,4,5];
Elements can be accessed by their index – a number representing the element’s position in the array. Indexing starts at 0. For example, the first element in the array has an index of 0, the second element has an index of 1, and so on.
Arrays can start off empty (contain no data) and elements can be added later; or can be created containing elements which can be added to, removed or changed later.
You can watch the video below to see how to create and use arrays and scroll down to see the sample code.
Arrays are very useful in any programming language. When you use a simple variable, you can only store one value. For example age = 17 or firstname = “Harry”. But what if you want to store a list of related values such as all the names of members in a family? That is where arrays come in handy. Take a look at the syntax in the sample code below.
Here is the HTML code:
<html> <head> <title>Arrays</title> <script src="script.js"></script> </head> <body> </body> </html>
// How to create an empty array var fruits = ; // How to add elements to an existing array one-by-one fruits = "apple"; fruits = "banana"; fruits = "orange"; // Each element has an index (position) // Indexing starts from 0 // How to create an array with elements in it var users = ["joe", "sally", "max", "alice"]; // How to modify an existing element in an array users = "tim"; // How to add an element to an array users = "lisa"; // How to access individual elements from an array console.log(users); // this will display "joe" console.log(users); // this will display "sally" console.log(users); // this will display "lisa"
Next tutorial: Array methods