JavaScript Arrays
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.
Creating Arrays
The easiest way to create an array is using an array literal
[].
const array_name = [item1, item2, ...];
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).
Looping Array Elements
The safest way to loop through an array is using a for
loop or the forEach() method.
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().
Summary
- Arrays are used to store multiple values in a single variable.
- Array indexes start at 0.
- Use
constto declare arrays. - The
lengthproperty 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?
Enjoying these tutorials?