Data Structures: Arrays
Learn how arrays can help in handling related data collections, supporting indexed access, nesting for structure, and built-in methods for manipulation,
There are many situations in which you will have a collection of related data. Say, for example, we had a roster of students in a classroom. One way we could store information about the individual students is to assign each to a variable.
var student1 = "Mary";var student2 = "Barbara";var student3 = "David";var student4 = "Alex";
But what about if you had hundreds of students? Assigning each student to a separate variable quickly becomes tedious. Thankfully, JavaScript has a few dedicated variable types for handling collections of data. Let’s begin to discuss one of them.
Arrays
A JavaScript array is a variable that can store multiple values. Those values are accessed using a numbered indexing scheme.
To make an empty array, assign brackets ([]
) after the variable declaration:
var emptyArray = [];
You can also assign values when creating the array by including them in between the brackets, with commas separating the values. Going back to our example, we can create an array named students
:
var students = ["Mary", "Barbara", "David", "Alex"];
The values in an array can be accessed by writing the name of the array followed by an index position with the following syntax:
//Logs "Barbara" to the consoleconsole.log(students[1]);
Arrays are zero indexed, meaning the first item in an array will have an index of 0
, the second item’s index will be 1
, and so forth. In an ...