Web Analytics

JavaScript Arrays

Beginner ~15 min read

What is an Array?

An array is a special variable, which can hold more than one value. It is a common data structure used to store ordered collections.

HTML
CSS
JS

Creating Arrays

The easiest way to create an array is using an array literal [].

const array_name = [item1, item2, ...];
Best Practice: Always declare arrays with const. This prevents accidental reassignment of the array variable itself (though you can still modify its elements).

Accessing Elements

You access an array element by referring to the index number.

Note: Array indexes start with 0. [0] is the first element. [1] is the second element.

The Length Property

The length property of an array returns the length of an array (the number of array elements).

HTML
CSS
JS

Looping Array Elements

The safest way to loop through an array is using a for loop or the forEach() method.

HTML
CSS
JS

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

To check if a variable is an array, you can use Array.isArray().

HTML
CSS
JS

Summary

  • Arrays are used to store multiple values in a single variable.
  • Array indexes start at 0.
  • Use const to declare arrays.
  • The length property returns the number of elements.
  • Use Array.isArray() to check if a variable is an array.

Quick Quiz

If an array has 5 elements, what is the index of the last element?

A
5
B
4
C
0
D
-1