Arrays in JavaScript

This tutorial explains how to create an array in JavaScript. An array is a data structure (a way of storing and organising data) which, unlike variables, can store more than one value at a time. For example, an array could store several string values or several numbers (whereas a variable could only store one string, or one number at a time). Arrays are like lists and each item in the array is called an element.

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:

        <script src="script.js"></script>



And here is the JavaScript code:

// How to create an empty array
var fruits = [];

// How to add elements to an existing array one-by-one
fruits[0] = "apple";
fruits[1] = "banana";
fruits[2] = "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[3] = "tim";

// How to add an element to an array
users[4] = "lisa";

// How to access individual elements from an array
console.log(users[0]); // this will display "joe"
console.log(users[1]); // this will display "sally"
console.log(users[4]); // this will display "lisa"

Next tutorial: Array methods

Leave a Reply