Arrays in JavaScript

Coding with JavaScript

🕑 This lesson will take about 10 minutes

In this lesson, you will learn how to create an array in JavaScript. An array is a data structure (a way of storing and organising data) that, 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 be empty to begin with (contain no data) and elements can be added later; or can be created containing elements that can be added to, removed or changed later.

Watch the video below to see how to create and use arrays and scroll down to view 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 = 20 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.

Sample HTML & JavaScript code

Next lesson: Array methods