Arrays in JavaScript

This tutorial explains how to set up and access the elements in an array in JavaScript. An array is a data structure which, unlike variables, can store more than one value. For example, an array could store several string values or several numbers. 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];

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 name = “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.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Arrays</title>
 <script type="text/javascript">
 
 // how to declare and initialise an array when you know the values
 var words = new Array("hello","hi","howdy","gday");
 
 // how to print an element from an array
 document.write(words[2]);
 
 // you can also declare an array by specifying the number of elements in the array without adding them eg.
 var pets = new Array(4);
 // and then add values later eg.
 pets[0]= "dog";
 pets[1]= "cat";
 pets[2]= "fish";
 pets[3]= "bird";
 
 // you can also start off with an empty array eg.
 
 var cars = new Array();
 
 // and then add values later
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // Some array hints:
 // each value is an element in an array
 // array elements are accessed using an index which starts from 0
 
// A shorter way of creating an array of integers:
var myNumbers = [1,2,3,4,5];
 
// A shorter way of creating an array of strings:
var myStrings = ["a","b","c"];
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Finding the length of arrays and strings

Leave a Reply